AJAX/JSON MVC method not being called - json

The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}

If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.

Related

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

How to post a form as a View Model object, along with other parameters to the controller in MVC? [duplicate]

This question already has answers here:
Mvc Jquery Ajax Post returns null
(2 answers)
Closed 6 years ago.
I have an action in controller as:
public int Edit(MyViewModel viewModel)
{
// code to edit
}
And I am posting a form as:
$.post("/MyController/Edit", $("#form").serialize()).then(
function () {
$("#dialog1").dialog("close");
$("#list-grid").trigger('reloadGrid');
});
This works fine. I get the parameter in the same format as MyViewModel .
However, I need to pass one more parameter to the action. So I have changed the controller to:
public int Edit(MyViewModel viewModel, string oldValue)
{
// code to edit
}
Now, I tried following way to pass the viewModel along with the oldValue to the action using an ajax call:
var object = $("#form").serialize();
$.ajax({
url: '#Url.Action("Edit", "MyController")',
type: "POST",
contentType: // please see below
data: { viewModel: object, oldValue: oldVal},
dataType: // please see below
contentType: 'application/json',
success: function (response) {
alert("Successfully updated!");
}
});
Although I am able to get the value of oldValue, the viewModel comes as null, although it is exactly the same as that sent in the $.post(...) , when examined in the console.
If I specify the contentType as any of:
application/x-www-form-urlencoded; charset=UTF-8 or,
application/json; charset=utf-8 or,
application/json
the call fails.
I have tried without specifying the dataType, and also by specifying it as a json, but in vain.
Creating a custom class for de-serializing the json sent is not doable.
How do I solve this?
Assuming that value of oldVal is not NULL. You can try this:
var object = $("#form").serialize();
$.ajax({
url: '#Url.Action("Edit", "MyController")',
type: "POST",
contentType: application/json; charset=utf-8 // please see below
data: JSON.stringify{ viewModel: object, oldValue: oldVal},
success: function (response) {
alert("Successfully updated!");
}
});
Add dataType: "JSON", before data: { viewModel: object, oldValue: oldVal}

Populate textbox with ajax call to server

I have first and last name text boxes, last name on blur triggers an ajax call to get additional data to fill in other textboxes. The call is made and I can see in the Chrome dev tool (network tab) that a json string is coming back with all the data, but I can't figure out how to populate the text fields.
ajax function:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
returns something like this:
{"EmployeeId":0,"FirstName":"Bob","LastName":"Smith","EmailAddress":null,"ManagerEmail":"Boss.Man#work.org","ManagerId":null,"ManagerFirst":"Boss","ManagerLast":"Man"}
The 'alert' shows "undefined".
You may just have a typo. Try changing "datatype" to "dataType"
You are trying to alert a data member of the response string, which does not exist. Instead, you should try to convert the string to object, like this:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
//converting it to object, since further rows expect this
data = $.parseJSON(data);
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
EDIT:
As Bryan Lewis pointed out, it was a typo. This has led to the behavior about which I have written my answer.
Turns out the problem was the server was returning an array of employee objects, so had to access it like:
data[0].ManagerFirst ... etc.
There was no way to tell that from the data I posted, so my apologies.
fyi, once I added that fix, I changed the the dataType param back to 'datatype' and it still worked fine.

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Select2 ajax is correctly calling webservice, but then doing nothing after

I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.