MVC Deserializes null to "null" (string)

I am passing an object from jQuery to the MVC3 controller via $ .ajax POST. During debugging using the developer tools, I can see the object that I am assigning to the ajax data property. The object contains properties whose value is null. When I debug the controller, the properties that were empty 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: ... }) 
+4
source share
1 answer

Yeap, this is a bad side effect when using the default binder. You could avoid this 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) { // ... } }); 

Remarks:

  • contentType: 'application/json' .
  • JSON.stringify around the data parameter to convert to a JSON string request.
+4
source

All Articles