前言

在项目中经常使用到DropDownList来显示数据库中的数据,典型的例子为为某书籍选择所属类型。

使用SelectList来实现:

实现一:

Controller 代码

SelectList selectList = new SelectList(bookshelper.GetCategoryList());
ViewData["Category"] = selectList;

View代码

@Html.DropDownList("Category",(SelectList) ViewData["Category"])

生成代码:

<select id="Category" name="Category">
  <option>ImageOfTaiWan.Entity.Category</option>
  <option>ImageOfTaiWan.Entity.Category</option>
  <option>ImageOfTaiWan.Entity.Category</option>
</select>

注意上面的选择列表实际上为选项类型了,并不是我们想要的具体内容。

那怎么搞呢?

实现二:

Controller代码:

SelectList selectList = new SelectList(
                                  bookshelper.GetCategoryList().Select(item =>item.Name));

View代码不变

生成Html代码:

<select id="Category" name="Category">
	<option>戏剧</option>
	<option>小说</option>
	<option>历史</option>
</select>

上述代码在页面上已经完全可以显示,但是如果再将表单提交到后台那么只能获取到具体的值,而我们需要的是值的ID。

这时候就需要使用SelectList的另外一个构造函数:

//
// 摘要:
//     使用列表的指定项、数据值字段、数据文本字段和选定的值来初始化 System.Web.Mvc.SelectList 类的新实例。
//
// 参数:
//   items:
//     各个项。
//
//   dataValueField:
//     数据值字段。
//
//   dataTextField:
//     数据文本字段。
//
//   selectedValue:
//     选定的值。
public SelectLit(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);

实现三:

将Controller代码修改为:

SelectList selectList = new SelectList(item, "Id","Name");
ViewData["Category"] = selectList;

生成的Html代码:

<select id="Category" name="Category">
	<option value="3">戏剧</option>
	<option value="2">小说</option>
	<option value="1">历史</option>
</select>

自此,我们已经完全实现了功能

如果是在编辑页,则需要让下拉列表框默认选择一项,那么这个功能需要为SelectList的构造函数添加第四个参数selectedValue

Entity.Books books = bookshelper.GetById(id);
var item = bookshelper.GetCategoryList();
SelectList selectList = new SelectList(item, "Id","Name",books.Category);
ViewData["Category"] = selectList;

则生成的html代码为:

<select id="Category" name="Category">
	<option value="3">戏剧</option>
	<option selected="selected" value="2">小说</option>
	<option value="1">历史</option>
</select>

使用SelectListItem来实现

实现四:

Controller代码:

IEnumerable<SelectListItem> items = 
bookshelper.GetCategoryList().Select(item => new SelectListItem { Value = item.Id.ToString(), Text = item.Name });

View代码:

@Html.DropDownList("Category",(IEnumerable<SelectListItem>) ViewData["Category"])

生成的Html代码:

<select id="Category" name="Category">
	<option value="3">戏剧</option>
	<option value="2">小说</option>
	<option value="1">历史</option>
</select>

2013年12月19日 14:05:13 更新

今天遇到问题是默认选项使用上面的方法怎么都选不中。

不知道是啥子原因,最好在网上看到这篇文章。http://www.daojia100.com/jingyan/info/50617f292e05e81684437e4a.aspx

所以在编辑页里得给对应的Id的表单元素添加其本身的ViewData[""]

具体是什么原因现在还不详!

 

posted on 2013-12-02 10:01  smallerpig  阅读(1169)  评论(0编辑  收藏  举报