use*_*680 5 asp.net asp.net-web-api
我的控制器能够创建模型对象,但是所有与模型相关的属性都被分配为空值
环境:VS 2010,最新的ASP.NET MVC RC,jQuery 1.7.1
以下是Web API控制器代码
public class Customer
{
public string Name { get; set; }
public string City { get; set; }
}
public class UserController : ApiController
{
public Customer Post(Customer user)
{
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是ajax调用代码
$.ajax('/api/user',
{
ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: 'json',
type: 'POST',
data: JSON.stringify({ "Name": "Scott", "City": "SC" })
});
Run Code Online (Sandbox Code Playgroud)
Controller会创建模型“ Customer”对象,但“ Name”和“ City”属性均为空。
怎么了
我已经在该站点上阅读了许多类似的问题,但是找不到解决方案。
我现在正在经历同样的问题。我不是 100% 确定答案,但下面是我的 javascript,我已将其添加到类 [DataModel] 和属性 [DataMember] 中。那是:
[DataModel]
public class Customer
{
[DataMember] public string Name { get; set; }
[DataMember] public string City { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和我的 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'));
});
});
});
Run Code Online (Sandbox Code Playgroud)