mvc 5 SelectList from table with empty value for DropDownList [英] mvc 5 SelectList from table with blank value for DropDownList

查看:16
本文介绍了mvc 5 SelectList from table with empty value for DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码来创建一个下拉

I am using below code to create a drop down

控制器

ViewBag.Id= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")

查看

 @Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control" })

我的问题是如何修改 SelectList 以添加一个空白项目,以便为 DropDownList 自动添加一个空白项目.

My question is how can I Modify SelectList to add a blank item so that there is a blank item automatically added for DropDownList.

谢谢.

推荐答案

使用 重载 接受 optionLabel

Use one of the overloads that accepts an optionLabel

@Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

或者如果您不想使用强类型方法

or if you do not want to use the strongly typed methods

@Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

这将添加第一个选项,其中包含在第三个参数中指定的文本和 null

Which will add the first option with the text specified in the 3rd parameter and with a null value

<option value="">Please Select</option>

这篇关于mvc 5 SelectList from table with empty value for DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆