我已經撰寫了這部分 ajax 代碼來發布一些將在資料庫中更新的資訊。
function postUpdateList() {
var id = $('#Id').val();
$.ajax({
url: `Home/EditPost/${id}`,
type:'POST',
contentType:"application/json;charset=utf-8",
dataType: JSON.stringify({ "Name": $('#name').val(), "Father": $('#father').val(), "Mother": $('#mother').val(), "Age": $('#age').val(), "Email": $('#email').val(), "Phone": $('#phone').val(), "Standard": $('#standard').val(), "Section": $('#section').val() }),
success: function (data) {
alert(data);
}
});
}
現在如何在我的控制器中接收這個 Json.stringify 物件并更新資料庫中的資訊?這是我的控制器方法:-
[HttpPost]
public JsonResult EditPost(int ID)
{
var data = "Updated SUccesfully";
return Json(data);
}
uj5u.com熱心網友回復:
與其他人有相同的想法,您需要修改預期ID從 URL 接收的 POST 操作,以及EditPostModel來自請求正文的物件。
[HttpPost]
public JsonResult EditPost(int ID, EditPostModel model)
{
var data = "Updated SUccesfully";
return Json(data);
}
public class EditPostModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Father { get; set; }
public string Mother { get; set; }
public int Age { get; set; }
// Following property
}
雖然 JavaScript 部分有一些錯誤,
需要一個前導
url斜杠。- 因此它將請求發送到
http://<your-domain>/Home/Post/{id}. - 如果沒有前導斜杠,請求將被發送到
http://<your-domain>/Home/Post/{id}/Home/Post/{id}不正確的位置。 - 參考:
uj5u.com熱心網友回復:
您的控制器通過此請求收到的是一個 json 物件,
它代表一個模型。(檢查您的瀏覽器工具的結構)
因此,最好的選擇是將
[FromBody] YourRequestModel model作為引數添加到您的操作中。uj5u.com熱心網友回復:
您必須為您的資料創建一個特殊的類并在控制器操作中使用 FromBody 屬性,還要添加 ID 屬性路由
[HttpPost("{ID}")] public JsonResult EditPost(int ID, [FromBody] List<StudentModel> data) return Json(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/503866.html標籤:网 json 阿贾克斯 asp.net-mvc asp.net-mvc-3
- 因此它將請求發送到
