Populating DropDownList with values showing error There is no ViewData item of type IEnumerable SelectListItem that has the key Name


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.


Asked by:- IIShriyaII
0
: 7618 At:- 4/18/2018 7:49:31 AM
MVC C# SQL







2 Answers
profileImage Answered by:- Vinnu

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

2
At:- 4/18/2018 1:47:29 PM
Its Doesn't work I'm still getting the same error 0
By : IIShriyaII - at :- 4/19/2018 12:30:08 PM
Can you comment down your error, add error screenshot with code so we can understand it more clearly, also, add a screenshot of your table(Roles) columns 0
By : vikas_jk - at :- 4/20/2018 8:22:31 AM
I fixed the error, but i think there is a problem with my roles, as I am Now getting an error that states: "Role adb2ba35-ef49-4726-a2ed-af149cc5bb77 does not exist.". When i check my AspNetRoles Tables that Role ID is present in that table. 0
By : IIShriyaII - at :- 4/20/2018 3:42:56 PM
Good to hear, you solved above issue, for new error you can upload the image of your roles table with code which is throwing error in a new question, with proper details so we can understand it and answer, you can mark accept the correct answer for this question after upvoting it, thanks 0
By : vikas_jk - at :- 4/21/2018 9:03:13 AM


profileImage Answered by:- manish

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.

1
At:- 4/20/2018 11:58:28 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use