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);
}
}