2012-07-18 44 views
0

我有一個表在我的數據庫,如:MVC 3自定義DropDownListFor項目

enter image description here

我想填補select標籤與使用Html.DropDownListFor()擴展MainTab項目。

最難的部分是,我希望這些項目是stringTabA_Name/TabB_Name/TabC_Name我該怎麼做?

回答

2

將視圖模型用於具有下拉列表的頁面。例如,

public class MyViewModel 
{ 
    /* You will keep all your dropdownlist items here */ 
    public IEnumerable<SelectListItem> Items { get; set; } 

    /* The selected value of dropdown will be here, when it is posted back */ 
    public String DropDownListResult   { get; set; } 

} 

在您的控制器中,您返回要查看的視圖模型,填寫列表並返回該模型。

public ActionResult Create() 
{ 
    /* Create viewmodel and fill the list */ 
    var model = new MyViewModel(); 

    // TODO : Select all data from MainTab to variable. Sth like below. 
    var data= unitOfWork.Reposityory.GetAll(); 

    /* Foreach of the MainTab entity create a SelectListItem */ 
    var dropDownListData = data.Select().(x = > new SelectListItem 
    { 
     /* Value of SelectListItem is the pk of MainTab entity. */ 
     Value = x.MainTabID, 

     /* This is the string you want to display in dropdown */ 
     Text = x.TabA.Name + "/" + x.TabB.Name + "/" + x.TabC.Name 
    }); 

    model.Items = new SelectList(dropdownListData, "Value", "Text"); 

    return View(model); 
} 

這是您的看法。

/* Make your view strongly typed via your view model */ 
@model MyNamespace.MyViewModel 

/* Define your dropdown such that the selected value is binded back to 
* DropDownListResult propery in your view model */ 
@Html.DropDownListFor(m => m.DropDownListResult, Model.Items) 

當您發表您的看法回到控制器,您的視圖模型應該有DropDownListResult that is filled with the selected dropdownlist item.