category类代码:
1 public partial class Category 2 { 3 public int CategoryId { get; set; } 4 public int CategoryTypeId { get; set; } 5 public string CategroyTitle { get; set; } 6 public int ParentId { get; set; } 7 }
News类代码:
public partial class News { public int Id { get; set; } public int CategoryId { get; set; } public int UserId { get; set; } public string Title { get; set; } public string Author { get; set; } public string Form { get; set; } public string Content { get; set; } public int SortId { get; set; } public Nullable<int> Clicks { get; set; } public bool IsLock { get; set; } public System.DateTime AddTime { get; set; } }
在News页面中显示所属分类下拉列表,下拉列表的value值和文本字段分别来自category表中的CategoryId和CategoryTitle
action方法中定义一个匿名类List,并绑定分类表(category)中的数据,因为下拉列表只要category表中的CategoryId和CategoryTitle的值,所以匿名List只需定义这两属性,注意:匿名List此时不需转换成SelectList
代码如下:
public ActionResult News() { List<Category>categoryList=base.CategoryBLL.Where().ToList(); ViewBag.selectList= categoryList.Select(c => new { id = c.CategoryId, name = c.CategroyTitle }); List<NewsView>newsList= AutoEntityMap<News,NewsView>.EntityMap(base.NewsBLL.Where().ToList()); return View(newsList); }
视图中利用DropDownListFor()显示列表代码如下:
1 @foreach (var item in Model) 2 { 3 var author=item.Author == null ? "佚名" : item.Author; 4 <tr> 5 <td><input type="checkbox" /></td> 6 <td>@Html.DisplayFor(Model => item.Id)</td> 7 <td><a href="#">@Html.DisplayFor(modelItmes => item.Title)</a></td> 8 <td>@Html.DropDownListFor(modelItmes => item.CategoryId, new SelectList(ViewBag.selectList,"id","name",item.CategoryId))</td> 9 <td class="am-hide-sm-only">@author</td> 10 <td class="am-hide-sm-only"></td> 11 <td> 12 <div class="am-btn-toolbar"> 13 <div class="am-btn-group am-btn-group-xs"> 14 <button class="am-btn am-btn-default am-btn-xs am-text-secondary"><span class="am-icon-pencil-square-o"></span> 编辑</button> 15 <button class="am-btn am-btn-default am-btn-xs am-hide-sm-only"><span class="am-icon-copy"></span> 复制</button> 16 <button class="am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only"><span class="am-icon-trash-o"></span> 删除</button> 17 </div> 18 </div> 19 </td> 20 </tr> 21 }
注意:“dataValueField”, “dataTextField”的名称必须与匿名List对象中的两个属性名相同;
本例中用到的SelectList构造函数如下:
1 // 2 // 摘要: 3 // Initializes a new instance of the System.Web.Mvc.SelectList class by using the 4 // specified items for the list, the data value field, the data text field, and 5 // a selected value. 6 // 7 // 参数: 8 // items: 9 // The items. 10 // 11 // dataValueField: 12 // The data value field. 13 // 14 // dataTextField: 15 // The data text field. 16 // 17 // selectedValue: 18 // The selected value. 19 public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);