tags:

views:

726

answers:

2

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.

A: 

I must admit, I have some confusion following exactly what you mean, so this is sort of a generic answer that might not be exact!

http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

This is a good read.

I can think of two ways.

To change the least amount of code, just put your ViewData in TempData and after the Redirect retrieve it.

The probably more accepted answer is to use the method described in the link above. Have your form post back to the same action. That action will have two implementations -- a Post and a Get. In the Post action, do all validation logic. If the validation works, do a redirect action to whatever view you display on success (Post-Redirect-Get pattern). If the validation fails, redisplay the same view of the form with the validation errors displayed.

If this isn't what you are asking, lemme know~

eyston
+3  A: 

Take the code you have for initializing the ViewData in the (GET) Add action, and refactor it (extract method) into a standalone, private method. Call that method from your (GET) Add action. Now in the POST action (which is, I presume, what you're showing above; it isn't clear) you can call the same, private method to populate ViewData. Now you no longer have any duplicated code. Remember that ViewData is a property of the Controller type, so you can set it anywhere, not just in the action method itself.

Craig Stuntz
Not tested this yet but it makes sense, didn't know you could do that outside an ActionResult method! Thanks
Shahin