I use MVC to check some html text fields on the 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 the check fails, it does not return the View argument ("Add"), because the controllers do not process the views in the return () view, and the option is to use RedirectToView ("viewname"); and that will work just fine. EXCLUDES that it does not tolerate checking the contents of AddModelError ("as if it were loading the page for the first time").
I can get around this by repeating the code to populate SelectList blocks before returning 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();
which works fine, however, I think there is a better way, rather than repeating this block of code, does anyone know of any way to return the redirected view and pass model errors to it?
Thanks in advance, hope he made some sense.
source share