2013-06-20 119 views
0

我有下面的模型說F:可枚舉對象MVC4

public partial class F 
{ 
    [Key, Display(Name = "Id")] 
    public int FId { get; set; } 

    public int RId { get; set; } 

    public int FTId { get; set; } 

    public string C { get; set; } 

    public string U { get; set; } 

    public string D { get; set; } 

    [ScaffoldColumn(false)] 
    public System.DateTimeOffset Created { get; set; } 

} 

在控制器我必須從數據庫中讀取的「F」的所有記錄,並指定那些記錄的一個枚舉列表。

對於前:

ViewBag.Cs = enumerable C column items (textbox) 
ViewBag.Us= enumerable U column items (textbox) 
ViewBag.FTIDs = enumerable FTId column items (this has to be a dropdown) 

在我我必須表明

@Html.Textbox(Cs); 
@Html.Dropdown(FTIDs); 

我只給了文本框和dropdows作爲一個例子,有可能像日期時間,複選框等許多其他控件, 我應該能夠將每列寫入viewbag列表並在MVC視圖中顯示它。

有人可以建議,如果這可以實現和如何?

非常感謝......

回答

0

不要使用viewbag這樣的事情 - 而不是強烈地結合您的視圖模型。只有使用視圖袋,如果你有一些真正的小傳..什麼複雜的,你應該總是使用強類型的視圖模型,你intellisence及其單元測試必須清潔

視圖模型:

Public class MyViewModel 
{ 
     public List<F> MyListOfFObjects { get; set; } 
} 

現在,當您創建視圖,你可以把它綁定到這個視圖模型,在彈出的,或者如果你不想重新創建它只需在視圖的頂部,將其添加引用,像這樣:

@model <your project>.<folder view model is in>.<view model name> 

例如

@model AdventureWorks.Models.EmployeeViewModel。

在你的控制器,你只需創建這個視圖模型,並把它傳遞給你的觀點,如:

public ActionResult Index() 
{ 
    MyViewModel vm = new MyViewModel(); 
    // Initialize your view model 
    // Get all the F objects from the database and populate the list 

    return View(vm); // now your view will have the view model 
} 

現在在視圖中,您可以通過這個視圖模型迭代

@foreach(var fObject in Model) 
{ 
    @Html.TextBoxFor(m => m.fId) 
    @Html.TextBoxFor(m => m.rID) 
} 

這裏是一個鏈接到您可以使用btw的不同@Html助手列表

http://qkview.com/techbrij/aspnet-mvc-4

參考強粘合視圖:

http://www.asp.net/mvc/tutorials/views/dynamic-v-strongly-typed-views