为什么不在TryUpdateModel更新时排除模型属性而不使用ModelState.Remove

时间:2011-10-18 09:01:58

标签: asp.net asp.net-mvc asp.net-mvc-3 modelstate

我正在尝试通过在控制器上使用以下代码排除某些属性来更新模型操作:

[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

说实话,我没有深入研究它,直接来这里向你们大喊这个问题。

1 个答案:

答案 0 :(得分:2)

您的模型Board上可能包含属性BoardAbbr。该消息来自已发布模型的验证(本例中为Board),与TryUpdateModel无关。因此,如果您删除模型上的属性,则消息将消失。

如果你将if(TryUpdateModel...放在一个if if this:

中,你可以看到发生了什么
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) {

但是你也可以确保没有可以绑定到属性的formvalue,绑定器不会为没有formvalues的属性生成消息。