遵循網上教程構建 ASP.NET MVC 應用,查詢、刪除功能正常,但表單提交新增數據時,Controller Action 參數屬性全為 `null`。調試發現 `Request.Form` 有值,但模型綁定未生效。懷疑與 JSON 序列化庫(如 LitJSON)衝突。
@* View *@
@using (Html.BeginForm("Create", "User", FormMethod.Post)) {
@Html.TextBoxFor(m => m.UserName)
@Html.TextBoxFor(m => m.Email)
}
@* Controller *@
[HttpPost]
[ValidateAntiForgeryToken] // 防 CSRF
public ActionResult Create(UserViewModel model) {
if (ModelState.IsValid) { /* 保存 */ }
return View(model);
}
// JS
$.ajax({
url: '/User/Create',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ UserName: 'Tom', Email: 'tom@test.com' }),
success: function(res) { /* ... */ }
});
// Controller
[HttpPost]
public ActionResult Create([FromBody] UserViewModel model) { // 必須加 [FromBody]
// ...
}
模型綁定失效多源於「約定不匹配」或「請求格式與綁定器不兼容」。優先使用強類型 HtmlHelper 生成表單,配合 `[HttpPost]`、`[ValidateAntiForgeryToken]`,遵循約定優於配置原則,可規避 90% 此類問題。