2014-10-29 26 views
0

我修改現有的代碼。將模型傳遞給RedirectToAction而不使用會話或tempdata?

從一個動作我使用RedirectToAction轉移執行控制到另一個動作。我也需要傳遞Model和RedirectToAction。我的想法是無法使用Session或tempData將模型傳遞給第二個動作而直接完成。但還是想問一下有沒有一種技術可以通過RedirectToAction傳遞模型?我不想將模型放入Session或TempData中。

感謝

+0

請過去的模型內容代碼和操作代碼初始化模式。 – Yehia 2014-10-29 02:44:10

+1

你可以使用其中一個接受'Object routeValues'的重載,但只有當你的模型的屬性是基本類型時(如果任何屬性是一個複合類型的集合,那麼它將會失敗),但是你真的應該得到模式從數據庫再次 – 2014-10-29 02:49:33

+0

另一個控制器內的其他操作方法? – noobed 2014-10-29 07:37:41

回答

1

您可以嘗試類似的東西,但它並不覺得自己像一個自然的動作:

public ActionResult Index() 
{ 
    return RedirectToAction("AnotherAction", new 
    { 
     Parameter1 = Parameter1, 
     Parameter2 = Parameter2, 

     }); 
} 

[HttpGet] 
public ActionResult AnotherAction(ModelClass model) 
{ 
    //model.Parameter1 
    //model.Parameter2 
    return View(model); 
} 
0

我希望以前的答案的代碼拋出一個異常嘗試時隱式地將parameter1和parameter2的對象轉換爲ModelClass。

這就是說,最好的方法是將實體的id傳遞給您的新操作,然後訪問您的存儲庫以使用已傳遞的id初始化模型。假設您已使用UserID屬性初始化了user

return RedirectToAction("NextAction", new { id = user.UserID }); 

然後在NextAction只是傳入ID

+1

如果'ModelClass'包含「Parameter1」和「Parameter2」屬性,則不會引發異常 – 2014-10-29 11:58:32

相關問題