0

コントローラの以下のコードでいくつかのプロパティを除外してモデルを更新しようとしていますアクション:

[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ですか?

正直なところ、私はそれをあまり掘り下げず、まっすぐここに来て、皆さんにこの質問を叫びました。

4

1 に答える 1

2

モデルBoardにはおそらくプロパティBoardAbbrがあります。このメッセージは、投稿されたモデル(この場合はBoard)の検証から送信され、TryUpdateModelとは関係ありません。したがって、モデルのプロパティを削除すると、メッセージは消えます。

次のようにifを中に入れると、何が起こっているかを確認できますif(TryUpdateModel...

if(!ModelState.IsValid) {
    if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" })) { 
  .....
    }
}

編集

あなたのコメントによると:Bind属性を持つプロパティを除外すると機能します:

public ActionResult Edit_post([Bind(Exclude="BoardAbbr")] Board board, int id) {

ただし、プロパティにバインドできるフォーム値が入っていないことを確認することもできます。バインダーは、フォーム値のないプロパティのメッセージを生成しません。

于 2011-10-18T10:50:43.333 に答える