2015-10-30 29 views
0

我是.NET MVC的新手,但花了大量的時間爬過SO上的其他帖子以找到我的問題的答案,但是我一直無法找到什麼。從下拉列表回來時發生錯誤.NET MVC 5

我正在擴展Identity 2.0示例項目。我已經能夠使用創建表單上的HTML幫助程序爲新的ApplicationUser實現下拉列表,但我無法移過一個錯誤「沒有類型爲'IEnumerable'的ViewData項目具有關鍵'TeamList' 」。我可以看到問題是什麼 - ApplicationUser的ViewModel和Model對Team屬性(ICollection)有不同的類型,但我不知道該怎麼做。

我的代碼是下面:

ApplicationUser型號段:

[Display(Name = "First Name")] 
    public string firstName { get; set; } 
    [Display(Name = "Last Name")] 
    public string lastName { get; set; } 
    [Display(Name = "Hawks Number")] 
    public int number { get; set; } 
    [Display(Name = "Successful Logins")] 
    public int successfulLogins { get; set; } 
    [Display(Name = "Password Status")] 
    public bool tempPassword { get; set; } 

    public virtual ICollection<Team> Teams { get; set; } 

片段從RegisterViewModel視圖模型

[Display(Name = "Assigned Teams")] 
    public ICollection<Team> Teams { get; set; } 

片段從UserAdminController控制器

// GET: /Users/Create 
    public async Task<ActionResult> Create() 
    { 
     //Get the list of Roles 
     ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name"); 
     //Get list of Teams 
     IdentityDB _db = new IdentityDB(); 
     ViewBag.Teams = new SelectList(_db.Teams, "Name", "Name"); 

     return View(); 
    } 

    // 
    // POST: /Users/Create 
    [HttpPost] 
    public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles) 
    { 
     IdentityDB _db = new IdentityDB(); 

     // TODO: RESOLVE ISSUE WITH TEAM SELECTION 

     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser 
      { 
       UserName = userViewModel.Email, 
       Email = userViewModel.Email, 
       firstName = userViewModel.firstName, 
       lastName = userViewModel.lastName, 
       number = userViewModel.number, 
       successfulLogins = 0, 
       tempPassword = true, 
      }; 
      var adminresult = await UserManager.CreateAsync(user, userViewModel.Password); 

      //Add User to the selected Roles 
      if (adminresult.Succeeded) 
      { 
       if (selectedRoles != null) 
       { 
        var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles); 
        if (!result.Succeeded) 
        { 
         ModelState.AddModelError("", result.Errors.First()); 
         ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name"); 
         return View(); 
        } 
       } 
      } 
      else 
      { 
       ModelState.AddModelError("", adminresult.Errors.First()); 
       ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name"); 
       return View(); 

      } 

摘錄從查看

<div class="form-group"> 
    @Html.LabelFor(m => m.Teams, new { @class = "col-md-2 control-label" }) 
    <div class="col-md-10"> 
     @Html.DropDownListFor(m => m.Teams, (IEnumerable<SelectListItem>)ViewBag.Teams, "- Please Select a Team -", new { @class = "form-control" }) 
    </div> 
</div> 

過了一段時間的移動過去「不能隱式轉換」的錯誤得到了這一點。我曾嘗試使用LINQ來嘗試查找團隊記錄,但當然ViewModel從來沒有拿起HTTP POST。

任何幫助將不勝感激。如果有更多的信息可以提供,請讓我知道。

+0

錯誤意味着你試圖綁定到'TeamList'(這沒有任何意義),而'TeamList'是'null'。你需要顯示你正在生成下拉列表的視圖部分(包括你在視圖中使用的模型) –

+0

謝謝@StephenMuecke - 我已經編輯了問題,現在包括查看信息。如果您需要更多信息,請讓我知道 - –

+0

您的模型中甚至沒有名爲'TeamList'的屬性。你所顯示的POST方法有一個你甚至沒有顯示過的「RegisterViewModel」參數。你需要顯示正確的代碼! –

回答

1

發生該錯誤是因爲在POST方法中,您返回視圖,但尚未重新分配一個值給ViewBag.Teams(如您在GET方法中那樣),因此它的值爲null。但是,您的下拉列表正試圖綁定到無法完成的集合(<select>元素僅回發其選定選項的值),綁定將始終失敗。

它從你的代碼中使用Teams,因爲不清楚其在POST方法沒有提及,但你需要您的視圖模式更改爲:

public class RegisterViewModel 
{ 
    [Display(Name = "Assigned Teams")] 
    [Required(ErrorMessage = "Please select a team")] 
    public string SelectedTeam { get; set; } 
    public SelectList TeamsList { get; set; } 
    .... 
} 

,然後在GET方法,初始化模型並返回它

RegisterViewModel model = new RegisterViewModel(); 
model.TeamsList = new SelectList(_db.Teams, "Name", "Name"); 
return View(model); 

,並在視圖

@Html.LabelFor(m => m.Teams, new { @class = "col-md-2 control-label" }) 
@Html.DropDownListFor(m => m.SelectedTeam, Model.TeamsList, "- Please Select a Team -", new { @class = "form-control" }) 
@Html.ValidationMessageFor(m => m.Teams) 

和在POST方法,如果你需要返回視圖,因爲ModelState無效,則返回視圖

[HttpPost] 
public async Task<ActionResult> Create(RegisterViewModel model, params string[] selectedRoles) 
{ 
    .... 
    // if you need to return the view, then 
    model.TeamsList = new SelectList(_db.Teams, "Name", "Name"); 
    return View(model); 
} 

旁註之前重新分配SelectList:由於您使用視圖模式,那麼它也應該包括用於選擇角色的屬性並從您的POST方法中刪除params string[] selectedRoles參數。

+0

謝謝@StephenMuecke - RegisterViewModel的初始化爲我觸發了它,以及將值返回給RegisterViewModel的位置。感謝您的耐心等待! –