How to RedirectToAction in ASP.NET MVC without losing request data *

Question

Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction.

One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.

As I require the form to contain the originally POSTed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters.

Answer

The solution is to use the TempData property to store the desired Request components.

For instance:

public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}

Then in your "Form" action you can go:

public ActionResult Form()
{
/* Declare viewData etc. */

if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}
return View("Form", viewData);
}
< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/1936/" >How to RedirectToAction in ASP.NET MVC without losing request data< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment