I Have populated the DropDownList with the roles from the AspNetRoles, when I am registering a new user and allocating a role an error is thown
"There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Name'."
My AccountController :
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.Roles, "Name", "Name");
return View();
}
//
// POST: /Account/Register
[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)
{
//Assign Role to user Here
result= await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles);
//Ends Here
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
The 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 am not quite sure why it is throwing an error, Please can anyone assist.
Looking at your above code, you aren't creating dropdown list from ViewBag properly, here is the code which should work
[AllowAnonymous]
public ActionResult Register()
{
//Try to pass Id, and Name of roles, with Item List as First argument
// I believe your roles Table as Two columns(Id, Name) one unique Id column ID
ViewBag.Name = new SelectList(context.Roles.ToList(), "Id", "Name");
return View();
}
In your razor View, Show dropdown as
@Html.DropDownList("Name", ViewBag.Name as SelectList, "Select Name")
It should work, let me know if it doesn't, thanks
Looking at your above error "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Name'"
There is no key as "Name" , means ViewData.Name doesn't exists when rendering Razor code into HTML
In your View try to write Razor Syntax as below
@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.Name, "Select ...")
When you write above Razor syntax, it looks in for IEnumerable<SelectListItem>
in ViewBag
with key Name,
So, in C#(I assume you have Roles table with Column "Name")
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
return View();
}
If the above answer, doesn't work for you, try to get data in ViewBag using C# controller like this
public ActionResult Index()
{
//Fetch managers
List<Person> managers = new List<Person>()
{
new Person() { Id = 1, Name = "Jisha"},
new Person() { Id = 2, Name = "James"},
new Person() { Id = 3, Name = "Pam"},
new Person() { Id = 4, Name = "Peter"}
};
ViewBag.Persons = new SelectList(managers, "Id", "Name");
return View(employee);
}
and then you can render dropdown list in Razor View as below
@Html.DropDownList("Persons", (SelectList)ViewBag.Persons, string.Empty)
https://dotnetfiddle.net/FQmM32
Above link also has online live sample for creating dropdown list using ViewBag,any of the above way should work for you, if not check your syntax properly, it is the only issue.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly