Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I maintain ModelState with RedirectToAction?

Tags:

c#

asp.net-mvc

How can I return the result of a different action or move the user to a different action if there is an error in my ModelState without losing my ModelState information?

The scenario is; Delete action accepts a POST from a DELETE form rendered by my Index Action/View. If there is an error in the Delete I want to move the user back to the Index Action/View and show the errors that are stored by the Delete action in the ViewData.ModelState. How can this be done in ASP.NET MVC?

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)] public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri) {     if (!ModelState.IsValid)         return Index(); //this needs to be replaced with something that works :)      return RedirectToAction("Index"); } 
like image 377
Eric Schoonover Avatar asked Nov 11 '08 00:11

Eric Schoonover


People also ask

How do you preserve ModelState errors across RedirectToAction?

Basically, use TempData to save and restore the ModelState object. However, it's a lot cleaner if you abstract this away into attributes. E.g. If you also want to pass the model along in TempData (as bigb suggested) then you can still do that too.

Can we pass model in RedirectToAction?

By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers. The data will then be handled in the other view and be strongly typed to the model you are passing through the redirect.

Why is my ModelState IsValid false?

IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.


1 Answers

Store your view data in TempData and retrieve it from there in your Index action, if it exists.

   ...    if (!ModelState.IsValid)        TempData["ViewData"] = ViewData;     RedirectToAction( "Index" ); }   public ActionResult Index()  {      if (TempData["ViewData"] != null)      {          ViewData = (ViewDataDictionary)TempData["ViewData"];      }       ...  } 

[EDIT] I checked the on-line source for MVC and it appears that the ViewData in the Controller is settable, so it is probably easiest just to transfer all of the ViewData, including the ModelState, to the Index action.

like image 160
tvanfosson Avatar answered Oct 08 '22 06:10

tvanfosson