MVC中DropDownListFor的使用注意事项

1、在MVC的View页面中使用DropDownListFor时当DropDownListFor是列表是通过后台ViewBag传过来时,当ViewBag中的Key与DropDownListFor一致时,选择项会始终在第一项,如:@Html.DropDownListFor(o => o.RoleType, ViewBag.RoleTypeas IEnumerable<SelectListItem>)(错误的写法)

2、正确的写法如下:

页面上:

 

@Html.DropDownListFor(o => o.RoleType, ViewBag.ddlroleType as IEnumerable<SelectListItem>)

 

后台Controller中:

 

var roleType = _dictionaryService.Where(o => o.IsDeleted == false && o.ParentId == roleTypeParent.Id)
                                 .ToList()
                                 .Select(o => new SelectListItem()
                                 {
                                     Text = o.Name.ToString(),
                                     Value = o.Id.ToString()
                                 });
ViewBag.ddlroleType = roleType;

 

posted @ 2015-06-13 17:35  小个子猫  阅读(642)  评论(0编辑  收藏  举报