MVC 下拉框DropDownList的使用

1.后台Controller构建数据:

 string strSql = @"select * from tb_e_GoodsQuestionType where IsDelete=0";
IList<GoodsQuestionTypeModel> list = SqlHelper.GetEntities<GoodsQuestionTypeModel>(strSql);//查出数据放到list实体集合中

            // 类型下拉信息
            IList<GoodsQuestionTypeModel> listData =  list == null ? new List<GoodsQuestionTypeModel>() : list;//判空
            listData.Insert(0, new GoodsQuestionTypeModel() { GoodsQuestionTypeId = 0, TypeName = "全部" });//插入请选择或全部项
              //参数1:实现了IEnumerable借口的数据集合,参数2:value属性名,参数3:text属性名,参数4:选中的value值[可省略表示选中默认第一项]
            SelectList typeData = new SelectList(listData, "GoodsQuestionTypeId", "TypeName", "6");
            ViewBag.GoodsQuestionTypeData = typeData;//或viewData
//当然也可以这么构建数据源集合
 List<SelectListItem> list = new List<SelectListItem> {

                new SelectListItem { Text = "启用", Value = "0",Selected = true},//让某项选中也可以在循环中判断符合条件选中

                new SelectListItem { Text = "禁用", Value = "1" } };

2.html代码

1).使用强类型Html.DropDownListFor//带For强类型,参数为lambda表达式

@using model GoodsQuestionTypeModel
@Html.DropDownListFor(q=>q.GoodsQuestionTypeId, ViewBag.GoodsQuestionTypeData as SelectList,"请选择",new { @class = "form-control input-sm" })

此方法如果model的GoodsQuestionTypeId有值,会选中此相关选项的

请选择,是加了一个默认选项,text为"请选择",value为"",可以不加此参数,在数据源加一样

new{}里添加各种附加属性信息,例如css,Id,name等

2).使用Html.DropDownList//不带for松散类型,参数为字符串

@Html.DropDownList("GoodsQuestionTypeId", ViewBag.GoodsQuestionTypeData as SelectList,"请选择", new { @class = "form-control input-sm" })

第一个参数为dropdownlist的name,如果new{}里没有定义Id,它的name和id都为GoodsQuestionTypeId

3)JS

$(funciton(){$('#selId').text("循环构建option放在这里")})

4)MVC的For循环

 <select>
@foreach (GoodsQuestionTypeModel item in ViewBag.GoodsQuestionTypeData as GoodsQuestionTypeModel)
{
<option selected="selected" value="item.value">item.text</option>
}
</select>

3.如何在列表中使用数据源,使其显示应有的选中值

Controller代码

            IList<GoodsQuestionTypeModel> listData = goodsQuestionManageService.GetQuestionTypeList();
            listData.Insert(0, new GoodsQuestionTypeModel() { GoodsQuestionTypeId = 0, TypeName = "请选择" });
            ViewBag.TypeList = listData;
foreach (var entity in Model)
{
SelectList typeData = new SelectList(ViewBag.TypeList, "GoodsQuestionTypeId", "TypeName",entity.GoodsQuestionTypeId);//在循环中构建和绑定数据源,循环改变要绑定的值
<tr>
@Html.Hidden("GoodsQuestionManageId", @entity.GoodsQuestionManageId)
<td class="text-right">@Html.TextBox("QuestionQuantity", @entity.QuestionQuantity, new { @class = "form-control input-sm Amount", style = "text-align:right;", onblur = "numblur(this);", oninput = "numKeyup(this);", onpropertychange = "numKeyup(this);" })</td>
<td>@Html.DropDownList("GoodsQuestionTypeId", typeData, new { @class = "form-control input-sm" })</td>
<td>@Html.TextArea("Remarks", @entity.Remarks, new { @class = "form-control input-sm", style = "resize: none;", rows = "1" })</td></tr>}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页