我發現了一些非常奇怪的東西,我希望有人能解釋這一點。爲什麼html.dropdownlist將第一個屬性選項設置爲選中狀態?
我有一個下拉列表:
<div class="form-group">
@Html.Label("Roll", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("UserRole",
RegistrationHandlers.FilterRoleAssignmentList(),
"Choose a role",
new { @class = "form-control", })
</div>
</div>
我的模型所包含的屬性的一大塊,但一個是衛浴套間爲枚舉屬性:
public OverWatchRoles UserRole { get; set; }
枚舉:
public enum OverWatchRoles
{
SuperDeveloper = 0,
Developer = 1,
SuperAdministrator = 2,
Administrator = 3,
Employee = 4
}
填充下拉列表的方法:
public static List<SelectListItem> FilterRoleAssignmentList()
{
var user = HttpContext.Current.User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var userRole = UserManager.GetRoles(user.GetUserId());
List<SelectListItem> roles = new List<SelectListItem>();
switch (userRole[0])
{
case "Developer":
roles = Enum.GetNames(typeof(OverWatchRoles))
.Where(f => f != OverWatchRoles.SuperDeveloper.ToString())
.Select(f => new SelectListItem { Value = f, Text = f, Selected = false }).ToList();
break;
case "Administrator":
roles = Enum.GetNames(typeof(OverWatchRoles))
.Where(f => f != OverWatchRoles.SuperDeveloper.ToString() && f != OverWatchRoles.Developer.ToString() && f != OverWatchRoles.SuperAdministrator.ToString())
.Select(f => new SelectListItem { Value = f, Text = f, Selected = false }).ToList();
break;
default:
roles = Enum.GetNames(typeof(OverWatchRoles))
.Select(f => new SelectListItem { Value = f, Text = f, Selected = false }).ToList();
break;
}
return roles;
}
問題:
我發現,當我有下拉列表=「UserRole的」,這是相同的名稱作爲該模型中的propetty則第一枚舉選項被默認選擇的名稱。當我更改下拉列表的名稱時,默認選定的值變爲「選擇角色」。
這是怎麼發生的?我如何解決它?我想要「選擇一個角色」作爲默認選擇的選項。
我剛學到新的東西,謝謝! – ThunD3eR