2012-08-31 22 views
1

我明白我可以使用ModelBinding做到這一點確定,但我想知道我是否可以使用ViewBag訪問ViewBag的控制器,可在一個視圖

我設置ViewBag屬性中查看

@{ 
ViewBag.WasPriorityCustomer = Model.PriorityCustomer == true; 
} 

不是優先客戶的用戶可以更改爲1,但我需要知道他們是否是優先客戶。

在控制器

[HttpPost] 
public ActionResult Save(MyModel model) 
{ 
    if (ViewBag.WasPriorityCustomer == false && model.PriorityCustomer == true) 
    { 
    //Thank you for becoming a priority customer 
    } 
} 

不幸的是ViewBag.WasPriorityCustomer總是空

+0

ViewBag價值目前還不清楚你想達到什麼目的? 'ViewBag'只能從Controller到View而不是其他方式。您需要將'WasPriorityCustomer'與您的表單一起發送到您的控制器。 – nemesv

回答

3

你只是試圖做的事情錯誤的方式:

您可以在動作設置ViewBag的價值,並在生成的視圖中使用它的值。

但是要從POST操作的視圖中獲取值,應該使用隱藏輸入。

類似的東西在視圖(未經測試):

@ {bool wasPriorityCustomer = Model.PriorityCustomer;} 

@Html.Hidden("wasPriorityCustomer", wasPriorityCustomer) 

和行動變得

[HttpPost] 
public ActionResult Save(MyModel model, bool wasPriorityCustomer) 

,或者你可以改變你的視圖模型,包括 「隱藏」 的價值。

,並使用@Html.HiddenFor(m => m.WasPriorityCustomer)

+0

如果我使用隱藏的輸入,那麼我需要更新視圖模型,如果不是絕對必要的,我不想這樣做 – DotnetDude

+0

@DotnetDude好了,我完成了答案,並給出了替代 –

+1

@DotnetDude。隱藏字段在這裏是適當的。咬住子彈並在模型中包含WaPriorityCustomer,或者將其作爲行動的參數。請不要爲此使用會話。 –

-1

試試這個代碼,如果你想存儲在viewBag一定的價值,並希望在這篇ViewBag值使用。

在示範行動

ViewBag.Test = ("NewTest"); 
在查看

你可以寫

@ViewBag.ProcedureTypeId 

這樣你就可以在Viewpage

相關問題