1

I have an MVC 5 website - with a controller. If the ModelState.IsValid - then I perform some actions.

If it's invalid I need to tell the user the error (in ViewBag.Message) - and pass the invalid model back to the view so the user can see and edit it.

so this works at the end of the controller action:

return View(MyModelName);

However - why does this also work?:

return View():

Why aren't I required to pass the invalid model back explicitly? Even this doesn't pass a blank model back to the view:

return View(new MyModelName());

I have to execute:

ModelState.Clear();

To get a blank model to the view. Can somebody explain to me why it behaves like this so I can understand what is going on.

I can find nothing on Google about this. Thanks.

niico
  • 11,206
  • 23
  • 78
  • 161

1 Answers1

1

Because it checks the ModelState dictionary first to see any values are there. If yes, those will be used to render the values for input fields of your form.

When you call ModelState.Clear(), It clears the model state dictionary. Since the model state dictionary is empty, now it will fallback to the model passed to the view and use that. That is the reason you will be able to see any updated property value of your view model in the view, If you update a property value in your action method and return to view.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thanks. So is there any reason to return View(MyModelName) - does that effectively just do the same thing? Is either best practice? – niico Sep 13 '16 at 14:49
  • Also why doesn't return View(new MyModelName()) result in a blank object being displayed? – niico Sep 13 '16 at 14:49
  • because it uses the model state dictionary – Shyju Sep 13 '16 at 14:49
  • So there's only a point in passing a model to a view if the model state dictionary is empty? What about a different populated model - would it still show the contents of the model state dictionary? – niico Sep 13 '16 at 14:52
  • Also is there ever a reason to return View(MyModelName) as opposed to return View()? – niico Sep 13 '16 at 14:56
  • 1
    Yes. For example, if your view model has a collection property which you use in your view to build the SELECT element ([like this example](http://stackoverflow.com/questions/10550420/how-to-read-the-data-from-a-dropdown-in-asp-net-mvc-3/10550556#10550556))using `Html.DropDownListFor` helper method, you need to reload this collection property value of your view model and send the view model object back. – Shyju Sep 13 '16 at 15:05