我正在使用 ASP.NET Core 6 MVC。如何通過 Ajax 將模型傳遞給控制器???我讀過這個,但我很困惑,并嘗試了下面顯示的代碼,但沒有任何運氣。任何幫助表示贊賞!提前謝謝了。
這是我對控制器的 Ajax 呼叫:
const fd = new FormData($('#form-data')[0]);
const data = {};
fd.forEach((value, key) => (data[key] = value));
console.log(data);
$.ajax({
type: 'POST',
url: '/User/Update_Me/',
data: data,
contentType: "application/json",
success: function (result)
{
alert('horeee');
},
error: function (result)
{
alert('error here');
}
這是我的UserController:
[HttpPost]
[Route("/User/Update_Me")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult Update_Me(Views.User.Data data)
{
if (!ModelState.IsValid)
return View(data);
// Starts process here ...
}
uj5u.com熱心網友回復:
在你的 js 代碼中,資料的型別是object,所以你需要改變你的 ajax 像:
$.ajax({
type: 'POST',
url: '/User/Update_Me/',
data: JSON.stringify(data),
contentType: "application/json",
success: function (result)
{
alert('horeee');
},
error: function (result)
{
alert('error here');
}
})
然后在行動中,您還需要添加[FromBody]屬性。
public IActionResult Update_Me([FromBody]Views.User.Data data)
{
if (!ModelState.IsValid)
return View(data);
// Starts process here ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/503862.html
