编辑:2017年10月31日
相同的代码/方法也可适用于Asp.Net Core 2.0。 主要区别在于,在asp.net core中,Web API控制器和Mvc控制器合并为单个控制器模型。 因此,您的返回类型可能是IActionResult
或其实现之一(例如:OkObjectResult
)。
使用
contentType:"application/json"
当您发送数据时,需要使用 JSON.stringify
方法将其转换为 JSON 字符串,
然后模型绑定器将把 JSON 数据绑定到您的类对象上。
下面的代码将正常工作(已测试)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
结果
![在此输入图片描述](https://istack.dev59.com/69yQt.webp)
contentType
属性告诉服务器我们发送的数据格式为 JSON。由于我们发送了一个 JSON 数据结构,所以模型绑定将正常进行。
如果你检查 Ajax 请求的头信息,你会看到 Content-Type
值被设置为 application/json
。
如果你没有显式指定 contentType,它将使用默认的 content type,即 application/x-www-form-urlencoded;
在 2015 年 11 月进行编辑,以解决评论中提出的其他可能问题
传递一个复杂的对象
假设您有一个复杂的视图模型类作为 Web API 操作方法参数,如下所示:
public class CreateUserViewModel
{
public int Id {set;get;}
public string Name {set;get;}
public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
public int Id {set;get;}
public string Code {set;get;}
}
而您的 Web API 终端点如下:
public class ProductController : Controller
{
[HttpPost]
public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
{
return m;
}
}
< p > < em > 在撰写本文时,ASP.NET MVC 6是最新的稳定版本,在MVC6中,Web api控制器和MVC控制器都继承自
Microsoft.AspNet.Mvc.Controller
基类。
要从客户端向方法发送数据,下面的代码应该可以正常工作
var model = {
Name: "Shyju",
Id: 123,
Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../product/save",
contentType: "application/json"
}).done(function(res) {
console.log('res', res);
});
模型绑定仅适用于某些属性,而非全部!为什么?
如果您没有使用 [FromBody]
特性来修饰 Web API 方法参数,则不会对所有属性进行绑定。
[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
return m;
}
发送模型(原生JavaScript对象,不是JSON格式),不指定contentType属性值
$.ajax({
type: "POST",
data: model,
url: "../product/save"
}).done(function (res) {
console.log('res', res);
});
模型绑定只适用于模型上的平面属性,而不适用于类型为复杂/其他类型的属性。在我们的情况下,Id
和Name
属性将正确地绑定到参数m
,但Tags
属性将成为一个空列表。
如果您正在使用短版本$.post
,发送请求时将使用默认的Content-Type,这会导致相同的问题出现。
$.post("../product/save", model, function (res) {
console.log('res', res);
});