I noticed that if there is an error when submit the form, it shows validation error message, that’s cool. However, it doesn’t keep my entered values. Actually, they are disappeared and even worse thing is datepicker won’t work either. So, I couldn’t use picker any more.
So, my questions are:
- how to preserve the values that I’ve entered before validation?
- if possible, any way to reuse picker control after validation error happened?
Assuming that you’re data binding your form values to a view model, just pass the view model back to the view when validation fails. Let’s look at an example:
The View Model:
The Controller:
The View:
We write the form HTML using the HtmlHelper methods
BeginFormandEditorForModel. We could useEditorFor(model => model.UserName)andEditorFor(model => model.Password)as well. Or we could just write the HTML out by hand. The important thing is that the HTML field names match the properties in our view model class:<input type="text" name="UserName" />ASP.NET Mvc will data bind the form elements to the LoginViewModel in the
HttpPostaction automatically. Just pass the invalid model back to the View to have the fields populate.