在ASP.NET MVC 3中将对象从一个操作方法传递到另一个操作方法

Jey*_*nne 2 c# asp.net-mvc-3

我在visual studio中使用ASP.NET和MVC 3,并且有一个关于将对象从一个操作方法(被调用Search)传递到另一个(被调用SearchResult)的问题.我尝试使用ViewData,但它没有坚持到ViewResult的视图.下面是我的代码片段,来自单个控制器.从表单收集数据并调用submit(因此[HttpPost]声明)时,将调用"Search" :

[HttpPost]
public ActionResult Search(Search_q Q){
 // do some work here, come up with an object of type 'Search_a' 
 // called 'search_answer'.
ViewData["search_answer"] = search_answer;
return RedirectToAction("SearchResults");
}

public ActionResult SearchResult(Search_a answer)
{   
return View(answer);
}
Run Code Online (Sandbox Code Playgroud)

我也尝试使用RedirectToAction("SearchResults", new {answer = search_answer});而不是上面调用RedirectToAction但我的'search_answer'仍然没有坚持到View.将此Search_a对象发送到SearchResultView 的最佳方法是什么?

Era*_*nga 7

您可以使用TempData传递对象.

[HttpPost]
public ActionResult Search(Search_q Q){
    // do some work here, come up with an object of type 'Search_a' 
     // called 'search_answer'.
     TempData["search_answer"] = search_answer;
     return RedirectToAction("SearchResult");
}

public ActionResult SearchResult()
{
    var answer = (Search_a)TempData["search_answer"];   
    return View(answer);
}
Run Code Online (Sandbox Code Playgroud)