mvc 5从表中选择列表,DropDownList的值为空白 [英] mvc 5 SelectList from table with blank value for DropDownList

查看:76
本文介绍了mvc 5从表中选择列表,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.

谢谢.

推荐答案

使用

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

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

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

将在第一个选项中添加第3个参数中指定的文本和一个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从表中选择列表,DropDownList的值为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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