Let’s say I have a HomeController which has an Index action, in the Index.cshtml View I will be posting back to an action in another controller (DocumentsController), after the action is completed I redirect back to Home/Index.
What is the recommended/cleanest approach to maintain the form values that the user has submitted in the Index.cshtml view? Given that it is being redirected from another controller?
EDIT: I’m presently using RedirectToAction:
return RedirectToAction("Index", "Home");
So using this approach how can I retain form values?
You can store the data in
TempDataorSession, callRedirectToAction, and then retrieve the values fromTempDataorSessionagain.TempDatais special. It stores stuff in Session, however, the data stored throughTempDatais only kept for the current request and a subsequent request. After that, the data is thrown out. It sounds well-suited for what you need, but if you need the data to stay around longer, just use Session.When you first visit
Home/Index,"SomeData"will be missing (null). When you visitDocuments/DoSomething, it will set"SomeData"to a string, then redirect you toHome/Index. At that point,Indexwill see the string we placed in"SomeData"and you can use it in yourIndexview. After that point however, all temp data will be cleared out.So, for example, if the user refreshed
Indexafter the redirect a bunch of times, the temp data would be missing during the refreshes. If that is not acceptable, then don’t use TempData, but keep it in the Session instead.