Friday, 20 April 2012

Without losing user requested data, how can we do RedirectToAction in ASP.NET MVC

When we are using ASP.NET MVC there should be some situations where we can require RedirectToAction.

Example: If we get any validation errors after form submission, we need to redirect back. that time it will reflect URL of the form, not action page.

using below code we can able to maintain original posted data as well as validation purpose. For this you can use RedirectToAction() method. we you use viewData parameter, all of the post parameters will be changed to Get parameters.

For this complex situaltion we can use TempData property for storing required request components.

public ActionResult SendData()
    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 
        and use it */
     return View("Form", viewData);

No comments:

Post a Comment

Please Give Your Valuable Comments on this Topic