在MVC 4中创建下拉列表的最佳方法是什么?

时间:2013-04-20 08:11:58

标签: asp.net-mvc-4 html.dropdownlistfor html-select viewdata viewbag

我想知道,在MVC 4中创建下拉列表的最佳方法是什么? 使用 ViewBag 或其他方法?

1 个答案:

答案 0 :(得分:10)

我认为,因为项目是视图中的变量值,它们属于视图模型。对于返回 out 的视图,视图模型不一定

型号:

public class SomethingModel
{
    public IEnumerable<SelectListItem> DropDownItems { get; set; }
    public String MySelection { get; set; }

    public SomethingModel()
    {
        DropDownItems = new List<SelectListItem>();
    }
}

控制器:

public ActionResult DoSomething()
{
    var model = new SomethingModel();        
    model.DropDownItems.Add(new SelectListItem { Text = "MyText", Value = "1" });
    return View(model)
}

查看:

@Html.DropDownListFor(m => m.MySelection, Model.DropDownItems)

在控制器中或在适合该场景的任何其他位置填充此内容。

或者,为了获得更大的灵活性,请为public IEnumerable<SelectListItem>切换public IEnumerable<MyCustomClass>,然后执行:

@Html.DropDownFor(m => m.MySelection,
    new SelectList(Model.DropDownItems, "KeyProperty", "ValueProperty")

在这种情况下,您当然还必须修改控制器操作,以便model.DropDownItems填充MyCustomClass实例。

相关问题