Reputation: 861
I'm passing an object from jQuery to a MVC3 Controller via a $.ajax POST. While debugging using Developer Tools, I can see the object I'm assigning to the ajax data property. The object contains properties whose value is null. When I debug the Controller, the properties which were null in the JS Debugger are now "null" (strings).
Why is this? What can I do to prevent this from happening?
C# Object
public class User
{
public string Name { get; set; }
}
Javascript Object
var user = {
Name: null
}
Controller Method
public JsonResult HelloWorld(User user) { .. some logic .. }
ajax Call
var data = user;
$.ajax({
url: '/Controller/HelloWorld/',
data: data,
type: 'post',
success: ...
error: ...
})
Upvotes: 4
Views: 723
Reputation: 1039578
Yeap, that's an unfortunate side effect with the default model binder. You could avoid it by either not including null properties in the request at all or by using a JSON request:
$.ajax({
url: '@Url.Action("HelloWorld", "Controller")',
data: JSON.stringify({ Name: null }),
contentType: 'application/json',
type: 'post',
success: function (result) {
// ...
}
});
Things to notice:
contentType: 'application/json'
.JSON.stringify
around the data parameter in order to convert to a JSON string the request.Upvotes: 4