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"); }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With