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;
原文地址:https://www.cnblogs.com/maocs/p/4573813.html