Pages

Tuesday, May 24, 2011

Passing data with RedirectToAction

This might be a result from the WebForms-centric way of thinking and a dirty habit, but I need to have the following flow on the web site:

  1. User clicks a button (or submits some data in another way)
  2. This posts the form to the Home controller.
  3. Home controller transfers the data to another controller's action

I tried using the default route's 'id' parameter but this puts a long XML into the address field in the browser and, besides, just doesn't work.

The right option for this scenario is using TempData. This translates to simply using 

            TempData.Add("customMessage", xmlContent);
            return RedirectToAction("Index""CustomMessage");

in the Home controller, and 

            var xmlContent = (string) TempData["customMessage"];

in the receiving controller. (Passing the same data to the view is another matter. Using ViewBag is the 'quick & dirty' way. See related post.)

"The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out."  

Source:

http://stackoverflow.com/questions/5753720/passing-info-to-another-action-using-redirecttoaction-mvc

2 comments:

John said...

Exactly what I was looking for - thanks for sharing!

Anonymous said...

Thanks!