コントローラの以下のコードでいくつかのプロパティを除外してモデルを更新しようとしていますアクション:
[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
、そのうちの1つです:
if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" }))
次に、メソッドの前に以下のコードを配置しますTryUpdateModel
。これは魅力のように機能します。
ModelState.Remove("BoardAbbr");
ここで私を悩ませているのは、私が何か間違ったことをしているのか、フレームワーク内に何か間違っていることが構築されているのかということです。私は最初のものがここでの問題であるに違いない。
TryUpdateModel
更新時にモデルプロパティを除外しないのはなぜModelState.Remove
ですか?
正直なところ、私はそれをあまり掘り下げず、まっすぐここに来て、皆さんにこの質問を叫びました。