Web API Model Properties: null

My Controller can create a model object, but all properties associated with the model are assigned to null values

Environment: VS 2010, ASP.NET MVC RC latest, jQuery 1.7.1

Below is the web API controller code

public class Customer { public string Name { get; set; } public string City { get; set; } } public class UserController : ApiController { public Customer Post(Customer user) { return user; } } 

Below is the ajax call code

 $.ajax('/api/user', { ContentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: 'json', type: 'POST', data: JSON.stringify({ "Name": "Scott", "City": "SC" }) }); 

The controller creates an object of the "Client" model, but the "Name" and "City" properties are equal to zero.

What is wrong here?

I read a lot of similar questions on this site, but could not find a solution.

+4
source share
4 answers

This blog provides a good overview of how Binding Binding differs in an ASP.NET web project and an ASP.NET Web API project.

I had a similar problem in the project I was working on, and adding an explicit ModelBinding attribute made the property values ​​stick to

Requested Data:

 var customer = { Name : "customer Name", City : "custome City" } $.ajax({ url : ... type: ... data : customer }); 

Request Class:

 public class Customer { public string Name { get; set; } public string City { get; set; } } 

Controller:

 public class UserController : ApiController { [HttpGet] public Customer Get([ModelBinder] Customer user) { // fetch from whereever } } 
+2
source

I am experiencing the same problem right now. I am not 100% sure of the answer, but below is my javascript, and I added to the [DataModel] class and [DataMember] properties. I.e:

  [DataModel] public class Customer { [DataMember] public string Name { get; set; } [DataMember] public string City { get; set; } } 

And my javascript

  $(document).ready(function () { // Send an AJAX request $.getJSON("api/session/GetAll", function (data) { // On success, 'data' contains a list of products. $.each(data, function (key, val) { //debugger; // Format the text to display. //var str = val.Name + ': $' + val.Price; var str = 'abcd'; // Add a list item for the product. $('<li/>', { text: str }) .appendTo($('#products')); }); }); }); 
+1
source

Faced a similar problem, and my problem turned out to be invalid JSON in the request body. A comma disappeared after one of the fields. Therefore, it seems that the default binder simply binds zero if there are syntax errors in the JSON.

0
source

The next time this happens, make sure that there is no “internal” keyword in the property setting. That is: instead of public string Comment {get; internal set;} public string Comment {get; internal set;} use public string Comment {get; set;} public string Comment {get; set;}

This fixed it for me.

0
source

All Articles