ASP.Net MVC Error: There is no ViewData item of type IEnumerable that has the key username

bigbear
 
on Apr 10, 2019 11:52 PM
Sample_120908.zip
4021 Views

I have a dropdownlist connected to a viewbag list and the correct list is displayed in the ddl. When I click my btn for a postback I get

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

I tried without a 'IEnumerable or just a SelectList() a few different ways and I haven't been able to get my method to work GetRolesForUser.

Any input would be appreciated. Here is what I have. 

                @using (Html.BeginForm("GetSelectedUserRole", "SuperAdmin"))
                {
                    @Html.AntiForgeryToken()
                    <div class="panel-body">
                        <div class="input-group">
                            <span class="input-group-addon">User Name</span>
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-user"></i>
                            </span>
                            @Html.DropDownList("username",(IEnumerable<SelectListItem>)ViewBag.SelectUsers, "Choose ...",new { @class = "form-control" })
                        </div>
                    </div>
                    <div class="panel-footer">
                        <input type="submit" value="Get Role" class="btn btn-primary" />
                    </div>
                }
                @if (ViewBag.RolesForUser != null)
                {
                    <div class="alert alert-info text-center">
                        <strong>Role for User</strong>
                        <ol style="list-style: decimal inside;">
                            @foreach (var role in ViewBag.Roles4User)
                            {
                                <li>@role</li>
                            }
                        </ol>
                    </div>
                } 

 

        public void UsersSelectList()
        {
            var usersList = (from users in context.Users
                             select new SelectListItem()
                             {
                                 Value = users.UserName.ToString(),
                                 Text = users.UserName
                             }).ToList();
            ViewBag.SelectUsers = usersList;
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetSelectedUserRole(string username)
        {
            AssignRolesModel rolesModel = new AssignRolesModel
            {
                lstAdmins = AdminList(),
                lstUsers = UserList()
            };

            if (!string.IsNullOrWhiteSpace(username))
            {
                var store = new UserStore<ApplicationUser>(context);
                var manager = new UserManager<ApplicationUser>(store);
                var user = manager.FindByName(username);
                var role = manager.GetRoles(user.Id).FirstOrDefault();
                if(role != null)
                {
                    ViewBag.Roles4User = role;
                    TempData["Success"] = "Roles Retrieved Successfully";
                    return View("AssignAdmin", rolesModel);
                }
                TempData["Error"] = "Role Retrieval Unsuccessful";
                return View("AssignAdmin", rolesModel);
            }
            else
            {
                TempData["Error"] = "Role Retrieval Unsuccessful";
                return View("AssignAdmin", rolesModel);
            }
        }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Apr 11, 2019 04:02 AM

Hi bigbear,

After post back you need to reassign the ViewBag.SelectUsers  i.e. call the UsersSelectList() method inside the GetSelectedUserRole ActionResult.

Check the below example.

Model

public class AssignRolesModel
{
    public List<SelectListItem> lstAdmins { get; set; }
    public List<SelectListItem> lstUsers { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        AssignRolesModel rolesModel = new AssignRolesModel
        {
            lstAdmins = AdminList(),
            lstUsers = UserList()
        };
        UsersSelectList();
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult GetSelectedUserRole(string username)
    {
        AssignRolesModel rolesModel = new AssignRolesModel
        {
            lstAdmins = AdminList(),
            lstUsers = UserList()
        };
        // Re-assigned the ViewBag object.
        UsersSelectList();
        // Do code of your condition.
        TempData["Message"] = username;
        return View("Index", rolesModel);
    }

    public List<SelectListItem> AdminList()
    {
        List<SelectListItem> lstAdmins = new List<SelectListItem>();
        lstAdmins.Add(new SelectListItem { Value = "1", Text = "Admin 1" });
        lstAdmins.Add(new SelectListItem { Value = "2", Text = "Admin 2" });
        lstAdmins.Add(new SelectListItem { Value = "3", Text = "Admin 3" });
        return lstAdmins;
    }

    public List<SelectListItem> UserList()
    {
        List<SelectListItem> lstUsers = new List<SelectListItem>();
        lstUsers.Add(new SelectListItem { Value = "1", Text = "User 1" });
        lstUsers.Add(new SelectListItem { Value = "2", Text = "User 2" });
        lstUsers.Add(new SelectListItem { Value = "3", Text = "User 3" });
        lstUsers.Add(new SelectListItem { Value = "4", Text = "User 4" });
        return lstUsers;
    }

    public void UsersSelectList()
    {
        var usersList = UserList();
        TempData["SelectUsers"] = usersList;
    }
}

View

<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
    <%using (Html.BeginForm("GetSelectedUserRole", "Home")) {%>
    <%:Html.AntiForgeryToken() %>
    <div class="panel-body">
        <div class="input-group">
            <span class="input-group-addon">User Name</span> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <%:Html.DropDownList("username", (IEnumerable<SelectListItem>)TempData["SelectUsers"], "Choose ...", new { @class = "form-control" })%>
        </div>
    </div>
    <div class="panel-footer"><input type="submit" value="Get Role" class="btn btn-primary" /></div>
    <%} %>
    <%if (TempData["Message"]!=null) {%>
        Selected User : <%=TempData["Message"]%>
    <%} %>
</body>
</html>

Screenshot