Validate and view ASP.NET MVC

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.

+4
source share
2 answers

Take the code that you have to initialize the ViewData in the Add action and reorganize it (the extract method) into a standalone private method. Call this method from your action (GET) Add. Now in the POST action (which I assume you are showing above is unclear), you can call the same private method to populate the ViewData. Now you no longer have duplicate code. Remember that ViewData is a property of type Controller, so you can set it anywhere, not just in the action method itself.

+4
source

I must admit, I have some confusion, following exactly what you mean, so this is a kind of general answer, which may not be accurate!

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 minimum amount of code, just put your ViewData in TempData and after receiving it.

Probably the more acceptable answer is to use the method described in the link above. Submit your form in the same action. This action will have two implementations - Post and Get. In the Post action, complete all validation logic. If validation works, perform the redirect action to any view that you show with success (Post-Redirect-Get template). If the verification fails, repeat the display of the same form type with the validation errors displayed.

If this is not what you are asking for, lemme know ~

0
source

All Articles