Reputation: 1
I've got a view model that has some text properties. And I use Html.DisplayFor to display them on the screen. But those text data won't be post back, so in the case of failed validation, the returned view won't have those data. How do I handle this kind of situation?
Thanks
Upvotes: 0
Views: 1820
Reputation: 149
ViewModel Preservers the state of what the user attempted to enter so if you simply redisplay the view return View(); it will return with the errant data in it the Validation Summary if it is being used will then enumerate required fields that do are not correct.
Upvotes: 0
Reputation: 3320
You need to create a new instance of the view model, populate it with the values you want to redisplay in the form, and send it back to the view:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProcessForm(FormCollection formValues)
{
...
// Perform validation, sending error messages to ModelState
...
if (!Model.IsValid)
{
AddressViewModel viewModel = new AddressViewModel
{
StreetAddress = formValues["StreetAddress"],
City = formValues["City"],
...
};
return View(viewModel);
}
}
Upvotes: 0
Reputation: 6725
you might add Html.HiddenFor() for every field that you want to be posted back
Upvotes: 2