Home » ASP » ASP.MVC » ModelState.Clear() is required to display back your model object

ModelState.Clear() is required to display back your model object

If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState.Clear() to clean the ModelState values.

The reason is that normally, you want to postback to the client the form with all the errors. So, when you put back the parameter that contain your model to the view to be returned, this one use the value of the ModelState.

So, for example, if I change a property and sent it back to the client :

[HttpPost]
public ActionResult Edit(MyObject objModel) 
{
	objModel.Property1 = "NEW VALUE";
	//...
	return View(objModel)
}

This won’t put on the UI the new value for the property1 because the ModelState values doesn’t contain this value but the one entered by the user.

To be able to override the model state you need to remove all the data from it.

[HttpPost]
public ActionResult Edit(MyObject objModel) 
{
	objModel.Property1 = "NEW VALUE";
	//...
	ModelState.Clear();
	return View(objModel)
}

To clear the memory of the model state you need to use ModelState.Clear(). You could also remove only the desired field by using method of ModelState.

ModelState.Remove("Property1");

Also, if you always want to not use the ModelState, you may want not to use HtmlHelper and directly use the model with Html code.

My Property: <input type="text" name="Property1" value="@Model.Property1" />

In all situation, what you need to remember is that ModelState is the default mechanism and will by default be the one that will be used to display information back to the form.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

6 Responses so far.

  1. Jacob says:

    Great explanation!

  2. kiril says:

    this answar was very clear i m steel new in c# and now i wonering why
    in this example i need to put in the view again user object when i put break points and trace the way of the form the informacion past from the model saveit in the database and why in the and of this litlle operacion or program callit how you want i need to put again user in this example in the view ” return View(users);” why this users must be here

    if (ModelState.IsValid)
    {
    using (PlatformDBContext db= new PlatformDBContext())
    {
    db.TableUsers.Add(users);
    db.SaveChanges();
    ModelState.Clear();
    TempData[“notice”] = “YOUR REGISTRACION WAS SACSESSFUL”;
    TempData[“Loged”] = users.UserName.ToString();
    return RedirectToAction(“index”,”Home”);
    }

    }
    return View(users);

  3. kiril says:

    sorry for my english here is the all

    [HttpGet]
    public ActionResult Index()
    {
    return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(TableUser users)
    {
    if (ModelState.IsValid)
    {
    using (PlatformDBContext db= new PlatformDBContext())
    {
    db.TableUsers.Add(users);
    db.SaveChanges();
    ModelState.Clear();
    TempData[“notice”] = “YOUR REGISTRACION….”;
    TempData[“Loged”] = users.UserName.ToString();
    return RedirectToAction(“index”,”Home”);
    }

    }
    return View(users);
    }

  4. Sam says:

    I think this article addresses a complex bug I am having but I still do not understand why this is needed.
    It seems like if the value is passed down by the VM to the user, and the user changes the value that is bound to the VM, and the user posts it back to the action that receives the VM, it should be updated. What am I missing? Plus my bug only happens after a certain series o clicks. Most of the time everything works but after this certain series of clicks, values from two clicks ago are bound, but the fresh values are displayed when I actually write them out.

    • ModelState has precedence over the View Model because its how MVC can handle validations. By clearing the ModelState, the data fall back to the provided View Model.

      I cannot help you more in regard to the series of clicks. This seems to be odd. Did you mean that depending on if your form has an error or not?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.