forum

Home / DeveloperSection / Forums / There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'UserName'

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'UserName'

Anonymous User1346419-Dec-2014

There is no ViewData item of type 'IEnumerable' that has the key 'UserName'. In view have 2 dropdownlists - for users and roles, after submitting i need to save role for choosen user. with role everything is ok, but trouble with user. i have list of users in list but i cant read slected for db. if use Html.TextBox("UserName") -it works, but admin will write username manually and it is not good. I am not an expert in MVC so apreciate any help. Controller:

 

    UsersContext db = new UsersContext();

 

    public ActionResult Index()

    {

        SelectList list = new SelectList(Roles.GetAllRoles());

        ViewBag.Roles = list;

 

        List<SelectListItem> items = new List<SelectListItem>();

        foreach (var user in db.UserProfiles.ToList())

        {

            SelectListItem li = new SelectListItem

            {

                Value = user.UserName,

                Text = user.UserName

            };

            items.Add(li);

        }

 

        ViewBag.UserName = items;

 

        return View(db.UserProfiles.ToList());

    }

 

    [HttpPost]

    [ValidateAntiForgeryToken]

    public ActionResult Index(string RoleName, string UserName)

    {

 

        SelectList list = new SelectList(Roles.GetAllRoles());

        ViewBag.Roles = list;

        return View();

    }

Model is of SimpleMembershipprovider, that is created with project.

 

View:

 

 @model IEnumerable<UserProfile>

 @Html.DropDownList("UserName", ViewBag.UserName as SelectList) - here mistake

What should i do to resolve?


Updated on 07-Jun-2016
I am a content writter !

Can you answer this question?


Answer

3 Answers

Liked By