views:

77

answers:

2

Hi Experts, In asp.net MVC application we have mechanism where, when we submit a form and if there is any problem with the values (validation fails), the form is displayed back maintaining old values. How does it happen ? Where are these values kept ? or they collected from FormCollection.

Help will be apprititated.

Regards Parminder

A: 

It really depends on how you set up your Controller Actions and your Views, because ASP.NET MVC looks in multiple places for the values.

Your assumption that it uses the FormCollection is kind of wrong, since the FormCollection is something that your controller Action takes in as a parameter and is totally separate from your View, where the values actually end up being displayed.

In 1.0, by default, the Edit template for views uses the 2nd parameter on most of the HtmlHelpers, like:

<%=Html.Textbox("Title", Model.ID)%>

This would have the old value pulled from the bound model object. So if you explicitly fail validation and return a View(object), the values would be pulled from that object. Still, if you are explicitly failing validation like:

if (ModelState.IsValid == false)
{
    return View();
}

Then the HtmlHelper code will likely result in an error, because no Model was bound.

If you completely leave off the 2nd parameter, like:

<%=Html.Textbox("Title")%>

The value will be pulled from the post (Request.Form) values.

Langdon
A: 

One way to do it is to use ModelState.AddModelError

A good tutorial on MVC Error handling can be found here

Alan Jackson