I'm using MVC to validate some html text boxes on a page, for example in my controller there is
if (String.IsNullOrEmpty(name))
{
ModelState.AddModelError("name", "You must specify a name.");
}
if (ViewData.ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View();
the problem is here, if validation fails, it fails returning View("Add") reason being controllers don't process views on return view(), an option would be to use RedirectToView("viewname"); and that'll work fine EXCEPT it doesn't carry through the validation AddModelError stuff ("it's as if loading the page for the first time").
I can get round this by repeating the code for populating SelectList boxes before the return View();
like this
ViewData["rooms"] = new SelectList(Villa.intList(10));
ViewData["sleeps"] = new SelectList(Villa.intList(20));
ViewData["accomodationType"] = new SelectList(accomodationList, "accomodationId", "accomodationType");
ViewData["regionName"] = new SelectList(regionList, "regionId", "regionName");
return View();
that works fine, however, I think there is a better way rather than repeating that block of code, does anyone know any way of returning a redirected view and passing it the model errors?
Thanks in advance, hope it made some kind of sense.