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 TempData or Session, call RedirectToAction, and then retrieve the values from TempData or Session again.
TempData is special. It stores stuff in Session, however, the data stored through TempData is 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.
public class HomeController : Controller
{
public ActionResult Index()
{
var someData = TempData["SomeData"] as string; // can be anything, using a string as an example;
return View(someData);
}
}
public class DocumentsController : Controller
{
public ActionResult DoSomething()
{
TempData["SomeData"] = "Hello, world!";
return RedirectToAction("Index", "Home");
}
}
When you first visit Home/Index, "SomeData" will be missing (null). When you visit Documents/DoSomething, it will set "SomeData" to a string, then redirect you to Home/Index. At that point, Index will see the string we placed in "SomeData" and you can use it in your Index view. After that point however, all temp data will be cleared out.
So, for example, if the user refreshed Index after 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.
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