MVC 3自定义DropDownListFor项目

时间:2012-07-18 18:28:01

标签: asp.net-mvc-3

我的数据库中有一张表:

enter image description here

我想使用select扩展名将MainTab标记用Html.DropDownListFor()项填充。

最难的部分是,我希望这些项目是string,如TabA_Name/TabB_Name/TabC_Name我该怎么做?

1 个答案:

答案 0 :(得分: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.