我有一个WebApi,它在Post方法中从我的网页接收数据: Api代码是:
public IHttpActionResult Post(PMSCost menu)
{
if (ModelState.IsValid)
{
try
{
if (menu.Price != 0)
return Ok(1);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
return BadRequest(ModelState);
}
Model类Code是:
public class PMSCost
{
public string CostName = "";
public int Price = 0;
}
我用代码调用WebAPi:
var datatosend = new Object();
datatosend.CostName = "Foooooo";
datatosend.Price = 100;
jQuery.ajaxSetup({ async: true });
$.ajax({
url: "/api/PMSCost/",
type: "Post",
data: datatosend,
success: function (data) {
if (data == "Success") {
alert("Success");
}
},
});
Api成功调用,但我发布到Api的PMSCost
变量(菜单)总是有空值,类似于CostName= ""
和Price= 0
。
有谁知道我的代码中有什么问题?提前谢谢
答案 0 :(得分:1)
如果要向操作发布数据,则必须添加[HttpPost]
属性:
[HttpPost]
public IHttpActionResult Post(PMSCost menu)
{
if (ModelState.IsValid)
{
try
{
if (menu.Price != 0)
return Ok(1);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
return BadRequest(ModelState);
}
AJAX请求如下:
var dataToSend = {
CostName: "Foo",
Price: 100
};
$.ajax({
url: "/api/PMSCost/",
type: "POST",
async:true,
contentType: "application/json",
data: JSON.stringify(dataToSend),
success: function (data) {
if (data == "Success") {
alert("Success");
}
}
});