我正在尝试通过在我的控制器 Action 上使用以下代码排除一些属性来更新模型:
[HttpPost, ValidateAntiForgeryToken, ActionName("Edit")]
public ActionResult Edit_post(Board board, int id) {
var model = _boardrepository.GetSingle(id);
#region _check if exists
if (model == null)
return HttpNotFound();
#endregion
if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" })) {
try {
_boardrepository.Edit(model);
_boardrepository.Save();
return RedirectToAction("details", new { id = id });
} catch (Exception ex) {
#region Log the error
ex.RaiseElmahNotification("Error while trying to update a destination.");
#endregion
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, inform your system administrator.");
}
}
return View(board);
}
当我尝试更新我的模型时,它会将我重定向到我的编辑视图并显示一条错误消息,指出该BoardAbbr
字段是必需的,如果我需要更新BoardAbbr
字段,这是完全合法的。但是正如您所看到的,我排除了一些带有以下代码的字段,并且BoardAbbr
是其中之一:
if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" }))
然后我把下面的代码放在TryUpdateModel
方法之前,它就像一个魅力:
ModelState.Remove("BoardAbbr");
令我困扰的是,要么我做错了什么,要么框架内部构建了一些错误。我敢打赌,第一个是这里的问题。
为什么在没有更新的情况下排除模型属性不TryUpdateModel
工作ModelState.Remove
?
老实说,我没有深入研究,直接来这里向你们喊这个问题。