在模型目录中,我有这个简单的模型:
{
// PUT: /User/Edit
[HttpPut]
public JsonResult Edit(int id, User user)
{
System.Diagnostics.Debug.WriteLine("Put request is working"); //не выполняется
return Json("Response from Edit");
}
}
在处理请求的文件夹控制器中,我有:
HttpPut
在文件Index.cshtml ajax代码中,它将 /*PUT*/
$.ajax({
url: '/User/Edit',
dataType: "json",
type: "PUT",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: 100, user: { name: 'Dmitry', email: 'dmitry@gmail.com' } }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data); //this message does NOT work
},
error: function (xhr) {
alert('error'); //This message shows
}
});
请求发送到控制器
POST
我应该添加什么?使用JSON的 $query = DB::table("fees9_items AS t1")
->select(array("t1.id", "i.item_description AS name",
DB::raw("SUM(t1.amount) as total"), "u.name AS unit"
)
->leftJoin("items AS i", "i.id", "=", "t1.item_id")
->leftJoin("mesure_units AS u", "u.id", "=", "i.unit")
->leftJoin("fees9 AS f", "f.id", "=", "t1.fees9_id")
->where("date", ">=", "2016-01-01")
->where(function($query){
$query->where("f.field1", "=", 1)
->orWhere("f.field2", "=", 2)
->orWhere("f.other", "=", 1)
)
->groupBy("i.id")
->get();
请求使用JSON,效果很好,问题仅在于Put请求
答案 0 :(得分:0)
id参数将从URL绑定,也不需要它,因为您可以将其直接包含在User
类中,因此请将其设为:
/*PUT*/
$.ajax({
url: '/User/Edit/100',
dataType: "json",
type: "PUT",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: 'Dmitry', email: 'dmitry@gmail.com' }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data); //this message does NOT work
},
error: function (xhr) {
alert('error'); //This message shows
}
});
或者你可以这样做
/*PUT*/
$.ajax({
url: '/User/Edit',
dataType: "json",
type: "PUT",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({id:100, name: 'Dmitry', email: 'dmitry@gmail.com' }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data); //this message does NOT work
},
error: function (xhr) {
alert('error'); //This message shows
}
});
控制器:
// PUT: /User/Edit
[HttpPut]
public JsonResult Edit(User user)
{
System.Diagnostics.Debug.WriteLine("Put request is working"); //не выполняется
return Json("Response from Edit");
}