MVC DropDownList

最近发现一个 MVC中绑定前台DropDownList ,

并且设置默认选中项的简单方法。

直接上代码


方案一

Action:

 ViewData["goodsTypeList"] = new SelectList(goodsTypeList, "id", "name", goodsTypeId);

1参数,是需要绑定的集合

2参数,DropDownList 的Value

3参数,DropDownList 的Text

4参数,默认值

存放到ViewData["goodsTypeList"] 


Html:

@Html.DropDownList("goodsTypeList")

这样默认就绑定了ViewData,并且会自动找到这个goodsTypeList,而且还设定了默认值。真的简单粗暴


方案二

Action

ViewData["goodsTypeList"] = new SelectList(goodsTypeList, "id", "name", goodsTypeId);


Html:

@Html.DropDownListFor(x => x.GoodTypes, (SelectList)ViewData["goodsTypeList"], new { Class = "input_width2 input_normal" })



原文地址:https://www.cnblogs.com/hanjun0612/p/9779881.html