My Controller is able to create the model object but all the properties related to model and assigned to null values
Environment : VS 2010, ASP.NET MVC RC latest, jQuery 1.7.1
Following 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;
}
}
Following is the ajax calling code
$.ajax('/api/user',
{
ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: 'json',
type: 'POST',
data: JSON.stringify({ "Name": "Scott", "City": "SC" })
});
Controller does create the model "Customer" object but both "Name" and "City" properties are null.
What's wrong here?
I have read many similar issues on this site but could not find the solution.
This blog here gives a good idea about how Model Binding differs in ASP.NET Web project and a ASP.NET Web API project.
I was facing a similar issue in the project I was working on and adding a explicit ModelBinding attribute made the property values stick
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
}
}
I'm going through the same issue right now. I'm not 100% sure of the answer, but below is my javascript and I've added to the class [DataModel] and to the Properties [DataMember]. That is:
[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'));
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With