MVC中DropDownListFor的使用注意事项

时间:2022-06-02 21:39:02

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;