【发布时间】:2012-12-14 14:50:12
【问题描述】:
我的控制器能够创建模型对象,但所有与模型相关的属性都分配给空值
环境: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;
}
}
下面是ajax调用代码
$.ajax('/api/user',
{
ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: 'json',
type: 'POST',
data: JSON.stringify({ "Name": "Scott", "City": "SC" })
});
Controller 确实创建了模型“Customer”对象,但“Name”和“City”属性均为空。
这里有什么问题?
我在这个网站上阅读了很多类似的问题,但找不到解决方案。
【问题讨论】:
-
由于类名是
Customer,我想说您还需要将传入的数据封装在Customer属性中。{"Customer" : { "Name": "Scott", "City": "SC" }}. -
感谢您的快速回复。我认为我们不需要传递类名。任何方式都试过了,我也有同样的问题。我也试过 {"user" : { "Name": "Scott", "City": "SC" }} 因为 user 是参数名称。
-
经过几次尝试,我已将 ajax 代码修改为 $.ajax('/api/user', { ContentType: "application/x-www-form-urlencoded; charset=UTF-8" ,数据类型:'json',类型:'POST',数据:{“名称”:“斯科特”,“城市”:“SC”}});我删除了 JSON.stringify 并且它起作用了。
-
把它写下来作为答案 - 不需要
JSON.stringify... -
问题在于您试图发布嵌入在表单 URL 编码数据中的 JSON 字符串。您应该选择其中一个。要么发送原始 JSON 并使用“application/json”媒体类型,要么使用“application/x-www-form-urlencoded”发送表单 URL 编码数据。请参阅stackoverflow.com/questions/5570747/jquery-posting-json 了解犯了同样错误的人。