I'm Trying to populate a DropDownList With Roles from my AspNetRoles table, in a Register form. When i hit Create i get this error :
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Name'.
AccountController.cs
- [AllowAnonymous]
- public ActionResult Register()
- {
- ViewBag.Name = new SelectList(context.Roles, "Name", "Name");
- return View();
- }
-
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Register(RegisterViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await UserManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
-
- result= await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles);
-
- await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
-
-
-
-
-
- return RedirectToAction("Index", "Home");
- }
- AddErrors(result);
- }
-
- return View(model);
- }
Register.cshtml
- @using System.Web.Mvc.Html
- @model YCS.Models.RegisterViewModel
- @{
- ViewBag.Title = "Register";
- }
- <h2>@ViewBag.Title.</h2>
- @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
- {
- @Html.AntiForgeryToken()
- <h4>Create a new account.</h4>
- <hr />
- @Html.ValidationSummary("", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
- </div>
- </div>
- <!--Select Role Type for User-->
- <div class="form-group">
- @Html.Label("Select User Type", new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @*@Html.DropDownList("Name")*@
- @Html.DropDownList("Name", (SelectList)ViewBag.Roles, "Select ...")
- @*@Html.DropDownListFor(m => m.UserRoles,new SelectList(ViewBag.UserRoles,"Value","Text"), new {@class="form-control"})*@
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" class="btn btn-default" value="Register" />
- </div>
- </div>
I've read most articles on the problem and still now solution, Please help.