2016-08-22 68 views
2

我發現了一些非常奇怪的東西,我希望有人能解釋這一點。爲什麼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則第一枚舉選項被默認選擇的名稱。當我更改下拉列表的名稱時,默認選定的值變爲「選擇角色」。

這是怎麼發生的?我如何解決它?我想要「選擇一個角色」作爲默認選擇的選項。

回答

5

這是一個不可空的枚舉屬性,所以它不能爲空。如果可以找到具有相同名稱的模型屬性,則該下拉列表將選擇該模型的值。

所以使模型屬性爲空的,所以它不會有SuperDeveloper默認值:

public OverWatchRoles? UserRole { get; set; } 

然後「選擇角色」將被顯示。

+0

我剛學到新的東西,謝謝! – ThunD3eR

1

只需添加到CodeCaster的答案。反編譯後Html.DropDownList我可以看到,在最後調用SelectExtensions.SelectInternal它使用默認值的情況下,匹配屬性名稱,如果它未能得到一個:

object defaultValue = allowMultiple ? htmlHelper.GetModelStateValue(fullHtmlFieldName, typeof (string[])) : htmlHelper.GetModelStateValue(fullHtmlFieldName, typeof (string)); 
    if (!flag && defaultValue == null && !string.IsNullOrEmpty(name)) 
    defaultValue = htmlHelper.ViewData.Eval(name); 
    if (defaultValue != null) 
    selectList = SelectExtensions.GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple); 
相關問題