tugberk
tugberk

Reputation: 58494

why doesn't Excluding model properties on update with TryUpdateModel work without ModelState.Remove

I am trying to update a model by excluding some properties with below code on my controller 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);
}

When I try to update my model, it redirects me to my edit view and display a error message saying that BoardAbbr field is required which is totally legitimate if I need to update BoardAbbr field. But as you can see I am excluding some fields with below code and BoardAbbr is one of them :

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

Then I put the below code before TryUpdateModel method, it works like a charm :

ModelState.Remove("BoardAbbr");

What is bothing me here is that either I am doing something wrong or there is something wrong has been built inside the framework. I bet that first one is the issue here.

why doesn't Excluding model properties on update with TryUpdateModel work without ModelState.Remove?

To be honest, I didn't dig into it so much and straightly come here to shout this question to you guys.

Upvotes: 0

Views: 1738

Answers (1)

John Landheer
John Landheer

Reputation: 4019

Your model Board probably has a property BoardAbbr on it. The message comes from validation of the posted model (Board in this case) and has nothing to do with TryUpdateModel. So if you remove the property on your model the message will go away.

You can see what is happening if you put your if(TryUpdateModel... inside an if like this:

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

EDIT

As per your comment: excluding the property with a Bind attribute will work:

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

But you could also make sure that there is no formvalue coming in that can be bound to the property, the binder will not generate message for properties without formvalues.

Upvotes: 2

Related Questions