2013-04-05 69 views
1

我有一個控制器已經收到POST回來,並且已經處理了用戶請求的內容。然後,我建立一個對象,而現在,想RedirectToAction ..在RedirectToAction中傳遞一個對象

return RedirectToAction() ("Index", "Location", r); 

其中R是很好命名對象,我有工作。但是在目標行動中,r是空的。

public ActionResult Index(LocationByAddressReply location) 

現在,我在這裏讀了幾篇關於這方面的文章,但我正在努力去理解。

的選項提出WASL

TempData["myObject"] = myObject; 

但似乎......奇怪。不安全。這是傳遞對象的最合適的方式嗎?

+0

RedirectToAction完全是它重定向你。您的替代方案可能是使用會話。 – AliK 2013-04-05 03:43:40

+1

你可以在你的'RedirectToAction(「Index」,「Location」,new {object myObject})中傳遞一個對象' – 2013-04-05 03:49:20

+0

關於這個問題的幾個問題:http:// stackoverflow。com/questions/1352015/redirecttoaction-with-complex-deep-object-failures http://stackoverflow.com/questions/9375279/how-to-pass-class-via-redirecttoaction – 2013-04-05 04:02:01

回答

2

是的,你可以使用TempData重定向獲得值。 你的方法應該是這樣的:

public ActionResult YourRedirectMethod() 

{ 
    TempData["myObject"]=r; 
    return RedirectToAction() ("Index", "Location"); 

} 

public ActionResult Index() 
{ 
    LocationByAddressReply location=null; 
    if(TempData["myObject"]!=null) 
    { 
      location=(LocationByAddressReply)TempData["myObject"]; 
    } 
} 

這樣你會得到你的模型是previousely對重定向方法設置的值。

+0

謝謝。我正在實施這個。您如何確保'TempData'商店不會太大?抓住它後取出物品? – Craig 2013-04-05 04:28:07

+0

TempData將自動變空。僅在當前和後續請求期間使用Temp數據。這是會話和tempdata之間的區別 – 2013-04-05 04:31:21

+0

有關更多信息,請參閱http://stackoverflow.com/questions/313572/what-is-tempdata-collection-used-for-in-asp-net-mvc。 – 2013-04-05 04:32:47

2

您可以通過兩種方式來實現:

首先選項,如果你有一個簡單的模型

​​

一個需要維護,想一想如果您稍後需要添加屬性你的模型。所以,你可以看中,做這樣的:

第二個選項UrlHelper是你的朋友

return Redirect(Url.Action("Index", "Location", model)); 

第二個選擇真的是這樣做的正確方法。 model是您構建並想要傳遞給您的對象LocationController

0

我不認爲使用TempData是正確的解決方案,請參閱this answer。您可以改爲傳遞由您的r對象組成的匿名對象。舉例來說,如果你有這樣的:

public class UserViewModel 
{ 
    public int Id { get; set; } 
    public string ReturnUrl { get; set; } 
} 

public ActionResult Index(UserViewModel uvm) 
{ 
    ... 
} 

你可以傳遞UserViewModel這樣的:

public ActionResult YourOtherAction(...) 
{ 
    ... 
    return RedirectToAction("Index", "Location", new 
               { 
                id = /*first field*/, 
                returnUrl = /*second field*/ 
               }); 
} 

ASP.NET MVC解析成你期待在Index操作參數的對象這一點。如果您還沒有切換使用TempData的代碼,請嘗試一下。