Reputation: 55333
I have this baffling and quite silly problem.
I have a weakly typed partial view in my MVC4 application. On it I have a button
<input type="button" class="btn btn-primary btn-lg" value="Find" id="fej-find" />
I send a jQuery ajax call from my controller to it like this
//searchedJob.Num = $("#fej-JobNumber").val();
//var DTO = { searchedJob: searchedJob };
var DTO = { searchedJobNumber: $("#fej-JobNumber").val() };
$.ajax({
data: JSON.stringify(DTO),
type: 'POST',
url: '@Url.Action("SearchJobs", "Jobs")',
success: function (msg) {
return alert(msg);
}
});
Firebug shows me this
But when I debug, my controller shows this.
Something is very wrong with my code. What could that be?
Upvotes: 0
Views: 1843
Reputation: 1039578
You don't need to JSON.stringify
anything. Just pass the value in the data
parameter with the same key as your action parameter name (searchedNumber
):
$.ajax({
url: '@Url.Action("SearchJobs", "Jobs")',
type: 'POST',
data: { searchedNumber: $("#fej-JobNumber").val() },
success: function (msg) {
alert(msg);
}
});
Also notice that you should not be returning any value from the success
callback.
You could use JSON when you want to send larger and more complex payloads to the server, like for example entire models. For example let's suppose that you have the following view model:
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<string> Tags { get; set; }
}
which your controller action takes as parameter:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
Now you could send it as JSON from the client:
var model = {
id: 5,
name: $('#some_input_field').val(),
tags: [ "tag1", "tag2", "tag3" ]
};
$.ajax({
url: '@Url.Action("SomeController", "SomeAction")',
data: JSON.stringify(model),
contentType: 'application/json',
success: function(result) {
alert(result);
}
});
Notice how in this case you need to set the proper Content-Type request header to application/json
so that the default model binder on the server will be able to automatically deserialize the request body payload to the corresponding view model.
Upvotes: 2