Get Json value from controller to jquery - javascript

I have a JS function:
$(document).on('click', '#submitForm', function (e) {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'bool',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
});
My action:
public ActionResult FileExist(string fileName)
{
bool result = true;
string path = Server.MapPath(TempPath) + fileName + ".xlsx"; //Path for the file
string[] Files = Directory.GetFiles(Server.MapPath(TempPath));
for (int i = 0; i < Files.Length; i++)
{
if (path == Files[i])
{
//The filename already exists
result = false;
}
}
return Json(new { returnvalue = result });
}
What am I doing wrong here? I'm trying to get the bool value from FileExist method, and if it's true stop the form from submitting (e.preventDefault)

There is no dataType: 'bool'. Please use dataType:'json' dataType:'text' to send the boolean values
In your case, it should be dataType:'json'
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'json',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
Then
[HttpPost]
public ActionResult FileExist(string fileName)
{
}

First, specify dataType: 'json' in your jquery ajax request:
$.ajax({
// <...>
dataType: 'json'
// <...>
});
If you would like to use HTTP GET:
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model, JsonRequestBehavior.AllowGet);
}
You can use HTTP POST method:
[HttpPost] // Add this attribute.
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model);
}

On top of your controller method, you have to put this annotation:
[HttpPost]

Add [HttpPost] to your controller,set dataType:'json' and set async:false in jquery ajax why do you need POST method. Just use GET method and add JsonRequestBehavior.AllowGet in your controller

put datatype asjson not bool ans also add [HttpPost] attribute on your action or other way is to put type:'GET'

The available data types in a service call are:
xml
html
script
json
jsonp
As per your code:
change the dataType to json as you are returning json from the server.
And by default the ActionResult will be using GET while in your ajax call you have specified POST.
So include [HttpPost] at the top of the method.

Related

How to pass HttpPostedFileBase from JavaScript as model instead of FormData

Is it possible to pass the form data with out using FormData by using the JavaScript Model. As my form has many controls I would like to go with Model approach instead of FormData.
Is there a way to pass selected files to controller with out using HttpPostedFileBase? I have nearly 10 different class which accepts HttpPostedFileBase
I have a class as follows in c#
public class ArtGallery{
Public string GallerName {get;set;}
Public HttpPostedFileBase[] Documents {get;set;}
}
The equivalent JavaScript Model is
class ArtGallery{
GallerName;
Documents[];
}
On my save of the form here is how I am doing it
function saveFormData(){
let gallery = new ArtGallery();
gallery.GallerName = "Test";
$.each($("input[type=file]"), function (i, obj) {
$.each(obj.files, function (j, file) {
gallery.Documents.push(file);
});
});
saveToDb();
}
function saveToDb() {
let url = "/MyController/PostData/";
$.ajax({
url: url,
type: 'POST',
async: false,
data: '{gallery : ' + JSON.stringify(gallery) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function (request) {
}
});
}
My controller is as follows, which is getting triggered but documents I am unable to get
[HttpPost]
public JsonResult PostUserData(ArtGallery gallery) {
}

Resource can not be found in Asp.NET although path is correct?

I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}

Convert JQuery ajax GET to POST

I have this jquery ajax get method on an Index razor in my application:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "GET",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
var count = 0;
$.each(data, function (index, value) {
$("#ulMessages").append("<li>" + value + "</li>");
count++;
});
// Assume validation errors if more than 1 message
if (count > 1) {
$("#btnSubmit").removeAttr("disabled");
}
}).fail(function () {
$("#ulMessages").append("<li>An error occurred. Please try again later</li>");
$("#btnSubmit").removeAttr("disabled");
}).always(function () {
$("#imgAjaxLoader").hide();
});
This calls a method within the api/project controller that returns a list of strings:
[HttpGet]
public List<string> SubmitProjectForPreapproval(int projectId)
{ ... }
What I want to do is convert this to an ajax post method. I've been struggling to do just that for the better part of the day. My question is, what is everything that needs to change in order for this to happen? e.g. - change attribute of the method to [HttpPost], and how do I send it the route value? (int pojectId)
Edit: If I do this it works for some reason:
public List<string> SubmitProjectForPreapproval(/*int projectId*/)
{
int projectId = 3308;
...
}
Not sure why it doesn't find my method if I have the parameter there.
I'm not sure how the #Url stuff formats with your system - but just changing it to something like:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
If you're bit:
#Url.Action("SubmitProjectForPreapproval
..actually has any ?xxx values in it, you also need to add them into the data: { ... }
The problem was indeed the way I was sending the data to the controller action. I fixed it by doing the following:
Alter the ajax method (make use of JSON.stringify):
var projectIdObject = {
ProjectId: "#ViewContext.RouteData.Values["ProjectId"]",
}
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: JSON.stringify(projectIdObject),
contentType: 'application/json',
}).done(function (data) { ... }
Add a class to take this stringified value:
public class ProjectIdObject
{
public string ProjectId { get; set; }
}
Alter the controller action method to receive this new object and extract the value I want:
[HttpPost]
public List<string> SubmitProjectForPreapproval(ProjectIdObject projectIdObject)
{
int projectId = int.Parse(projectIdObject.ProjectId);
...
}

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

Categories