在客户端:
var data = {Title":"Some Title","Description":"Something"} ;
$.support.cors = true;
$.ajax({
type: 'POST',
dataType: 'json',
url: apiUrl + "/Save",
data: data,
contentType: 'application/x-www-form-urlencoded',
success: function (returnedData) {},
error: function (xhr, ajaxOptions, thrownError) {},
processData: false,
async: false
});
在服务器端:
[HttpPost]
public ActionResult Save(DataModel data)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return null;
}
这是DataModel:
public class DataModel
{
public string Title { get; set; }
public string Description { get; set; }
}
一切正常。但是,当它向“保存”控制器操作发出POST请求时,模型上的属性始终为null,而不是从客户端获取值。
请注意,这是对我网站“子域”的跨域请求(即从example.com调用api.example.com)
我缺少什么?
提前全部谢谢!
答案 0 :(得分:1)
首先,使用以下选项更改您的ajax请求:
contentType : 'application/json', dataType: 'json'.
之后,将此控制器方法添加到控制器:
[HttpOptions]
public ActionResult Save()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return null;
}