2015-11-05 112 views
0

如果我有內部控制器的多條ViewBag線使用ViewBag作爲對象

ViewBag.ShowElement1 = myObj.IsAllowed; 
ViewBag.PageLabel = someotherObj.PersonName; 
.... 

我內部視圖當然使用的訪問某些值不知有任何更好的解決方案來包裝成1個邏輯塊這個所以我可以在裏面查看訪問諸如

ViewBag.MyRestricts.ShowElement1 
ViewBag.MyRestricts.ShowElement8 
+2

創建一個類,並使用一個類?我覺得你可能會濫用ViewBag。 – DavidG

+0

這不是一個好習慣嗎?只是詢問 – user1765862

+0

它看起來像你試圖傳遞一堆數據到你的視圖,你不能只使用視圖模型? – DavidG

回答

3

最佳的解決方案將是,如果你將創建一個視圖模型添加任何東西,你查看需要it.And然後創建使用ViewModel模型的強類型視圖。

一個視圖 - 一個視圖模型 .Anything您查看需要它必須在視圖模型

有一些規則。

規則#1 - 所有視圖都是強類型
規則#2 - 每個視圖模型類型,定義只有一個強類型 查看
規則#3 - 視圖決定了視圖模型的設計。只有需要
才能呈現一個View,並傳入ViewModel。
規則#4 - 視圖模型只包含有關查看

enter image description here

這是一個很好的post.I覺得會interestring的數據和行爲,你 https://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

0

爲什麼不你使用ViewModel呢?您可以定義一個類,如ShowElement1和pageLabel與屬性,然後在頂部加入這一行訪問該視圖:

@model TheTypeOfYourClass 

然後,你可以用@Model.PageLabel訪問屬性。

0

正如之前所說,這裏最好的解決方案是使用ViewModel,因爲使用沉重的視圖包被認爲是不好的做法。你可以閱讀有關這個​​here,我完全同意這個職位同意:

這裏是視圖模型將如何看起來像:

namespace MyProject.Models 
{ 
    public class MyViewModel 
    { 
     public bool ShowElement1 { get; set; } 
     public string PageLabel { get; set; } 
    } 
} 

這裏是控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      ShowElement1 = myObj.IsAllowed, 
      PageLabel = someotherObj.PersonName 
     }; 

     return View(model); 
    } 
} 

而且你的看法將是什麼像這樣:

@model MyProject.Models.MyViewModel 

<p>ShowElement1 value: @Model.ShowElement1</p> 
<p>PageLabel value: @Model.PageLabel </p> 
+0

我懷疑這將是一個更好的解決方案,因爲最有可能的模型已經被使用並且視圖包含視圖相關數據。 –

-1

您可以使用anonymouse對象

ViewBag.MyRestricts = new { ShowElement1 = true, ShowElement2 = false, }; 

,或者你可以創建爲

public class Restricts 
{ 
    public bool ShowElement1 { get; set; } 
    public bool ShowElement8 { get; set; } 
} 
ViewBag.MyRestricts = new Restricts { ShowElement1 = true, ShowElement2 = false, }; 

,並在您的視圖

var restricts = (Restricts)ViewBag.MyRestricts; 
if (restricts.ShowElement1) 
    ....