问题
Possible Duplicate:
pass data from Action To Another Action
I have a view in which I submit a form and depending on the results I want to redirect to an action. The view that correspondes to and action is strongly-typed and it should accept a ResultsViewModel.
I'm trying to pass the ResultsViewModel using T4MVC.
Below is the code:
[HttpPost]
public virtual ActionResult AddEntity(string viewModel)
{
//Deserialize using Json.NET
var entity = JsonConvert.DeserializeObject<MyEntity>(viewModel);
var success = DoSomething(); //returns boolean
if(success)
{
var result = new ResultsViewModel { MyEntity = entity, MessageId = 1};
return RedirectToAction(MVC.MyController.ResultsPage(result));
}
var result = new ResultsViewModel { MyEntity = entity, MessageId = 2};
return RedirectToAction(MVC.MyController.ResultsPage(result));
}
public virtual ActionResult ResultsPage(ResultsViewModel viewModel)
{
return View(viewModel);
}
When the code reaches
public virtual ActionResult ResultsPage(ResultsViewModel viewModel)
{
return View(viewModel);
}
viewModel is always equal to null.
I know I can do something like this:
return RedirectToAction("ResultsPage", new { viewModel = result });
EDIT: I tried the return RedirectToAction("ResultsPage", new { viewModel = result }); and I'm also getting a null in my viewModel.
However I'm trying to figure out why/how to pass an object using T4MVC.
Thanks,
回答1:
Use TempData
[HttpPost]
public virtual ActionResult AddEntity(string viewModel)
{
//Deserialize using Json.NET
var entity = JsonConvert.DeserializeObject<MyEntity>(viewModel);
var success = DoSomething(); //returns boolean
if(success)
{
var result = new ResultsViewModel { MyEntity = entity, MessageId = 1};
return RedirectToAction(MVC.MyController.ResultsPage(result));
}
var result = new ResultsViewModel { MyEntity = entity, MessageId = 2};
TempData["Result"] = result;
return RedirectToAction(MVC.MyController.ResultsPage(result));
}
public virtual ActionResult ResultsPage()
{
ResultsViewModel model = (ResultsViewModel)TempData["Result"];
return View(model);
}
来源:https://stackoverflow.com/questions/11111555/pass-an-object-in-redirecttoaction-using-t4mvc