This should be simple, but the answer is eluding me. If I’ve got a Save action in my controller, and the save fails, how do I cancel the action without disturbing what the user entered? For example, Index is strongly-typed of “MyTable”:
Function Index() As ActionResult
ViewData("message") = "Hello"
Return View(New MyTable)
End Function
<ActionName("Index"), AcceptVerbs(HttpVerbs.Post)> _
Function Save(ByVal form As MyTable) As ActionResult
Try
SaveMyData(form)
Return RedirectToAction("Index")
Catch
AddModelError("form", "An error occurred.")
???
End Try
End Function
In the Catch, if I put Return View(form), I lose the message passed via ViewData. If I redirect to Index, I’ll lose what the user entered. I think I’ve seen the simple (correct) way to handle this before, but if you don’t know what to search for, it’s hard to find. What am I missing?
From my understanding, you’re not losing the message passed via ViewData – that function simply doesn’t run.
And I would highly advise against doing a redirect or using TempData for what you’re trying to achieve, there is just no point in it and not the way MVC is supposed to work.
Going on what you’ve got I would have a private function that both actions call to return the view. It has your ViewData(“message”) in one place and you still have the previous values in the form (and inside ModelState like Josh E said).
WARNING: VB.NET air code from a C# programmer 😉
HTHs,
Charles
Ps. I would just like to add that I find it odd you’ve got an index page that posts back to itself and then if the post has errors it redisplays the index page BUT if there aren’t any errors it redirects back to the index page.
I don’t know what the app is doing but it does seem like you’re using the index page/view for far too many things.