首页 > 代码库 > [转]Html.DropDownList()的用法 ( Asp.Net MVC)
[转]Html.DropDownList()的用法 ( Asp.Net MVC)
Html.DropDownList()赋默认值:页面代码如下: <% List<SelectListItem> list = new List<SelectListItem> { new SelectListItem { Text = "启用", Value = "http://www.mamicode.com/0",Selected = true}, new SelectListItem { Text = "禁用", Value = "http://www.mamicode.com/1" } }; %>//list储存dropdownlist的默认值 <%=Html.DropDownList("state",list,Model.state) %> //state为实体的属性,默认选中"启用"Html.DropDownList()从数据库读取值:页面代码如下:<%= Html.DropDownList("Category", ViewData["Categories"] as SelectList,"--请选择--",new { @class = "my-select-css-class" } )%>Controllers代码:public ActionResult Create() { List<Category> categories = categoryService.GetAll(); ViewData["Categories"] = new SelectList(categories, "Id", "Name"); return View();} •原型一:public static string DropDownList(this HtmlHelper htmlHelper, string name){ IEnumerable<SelectListItem> selectData = http://www.mamicode.com/htmlHelper.GetSelectData(name);"001", Value = "http://www.mamicode.com/1", Selected = false });items.Add(new SelectListItem() {Text = "002", Value = "http://www.mamicode.com/2", Selected = false });ViewData["items"] = items; 简化后: var items = new List<SelectListItem>(){ (new SelectListItem() {Text = "001", Value = "http://www.mamicode.com/1", Selected = false}), (new SelectListItem() {Text = "002", Value = "http://www.mamicode.com/2", Selected = false})};将items值给ViewData:ViewData["items"] = items; 在aspx中这样使用:<%= Html.DropDownList("items") %> 生成的代码中,items将作为<select>标签的name和id值。 •原型二:public static string DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList){ return htmlHelper.DropDownList(name, selectList, null);}使用方法:<%= Html.DropDownList("items", new List<SelectListItem>{ (new SelectListItem() {Text = "001", Value = "http://www.mamicode.com/1", Selected = false}), (new SelectListItem() {Text = "002", Value = "http://www.mamicode.com/2", Selected = false})})%>在这里,不需要ViewData传入值,第一个参数items作为标签的name和id的值。items也可以是任意的字符串。•原型三public static string DropDownList(this HtmlHelper htmlHelper, string name, string optionLabel){ IEnumerable<SelectListItem> selectData = http://www.mamicode.com/htmlHelper.GetSelectData(name);>
[转]Html.DropDownList()的用法 ( Asp.Net MVC)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。