tags:

views:

189

answers:

2

I have a form, when user submit the form, I want to direct the user the new view to display the submitted result(transfer viewmode data to display view).

public class HomeController : Controller
    {
        private MyViewModel _vm;
        .....

        // POST: /Home/Create        
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(MyViewModel vm){
           //.....
           //set up vm to temp data _vm
           _vm = vm;

           return RedirectToAction("DisplayData");
        }
        // GET: /Home/DisplayData
        public ActionResult DisplayData()
        {
           //get temp data for display
           return View(_vm);
        }
}

When I posted the form, I can create vm and put it to temp data place _vm. But this _vm can be sent to another action DisplayData, it's null in action DisplayData(). It seems that when redirect action even in same controller, _vm is lost although it is Controller var, not action method var.

How to resolve this problem?

+2  A: 

It creates a new instance of the controller as it is a new request therefore as you have found it will be null. You could use TempData to store the vm, TempData persists the data for 1 request only

Good explanation here

redsquare
A: 

One good way is to call

return DisplayData(_vm)

instead of

RedirectToAction("DisplayData")

DisplayData should accept a model anyway.

Malcolm Frexner
but then you lose the Post, Redirect, Get Pattern
redsquare
RedirectToAction("DisplayData") will be back the current view with post action.
KentZhou
@KentZhou not sure I understand you. When you redirect the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. It wont do a Post.
redsquare
If use RedirectToAction("DisplayData"), need a action to macth it. If the action is public ActionResult DisplayData(), I even can't pass compile. If the action is public ActionResult DisplayData(MyViewModel vm), it will back the for form view, not the displaydata view. This is my trying result for different scenarios.
KentZhou