0

我的数据库中有一张表,例如:

在此处输入图像描述

我想用扩展名填充select标签。MainTabHtml.DropDownListFor()

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

4

1 回答 1

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.

于 2012-07-18T18:44:05.737 回答