'Proper way to use ViewBag for selectlist
I am getting an error on my selectlist when I open the form. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList''
I have tried other ways of doing this but always get some error. The other way gave an error on submit. In this case it wont load the page.
Here is my model.
[Required(ErrorMessage = "The Roles is required")]
public string Role { get; set; }
This is my controller:
public ActionResult RegisterUser()
{
RegisterViewModel objRegisterViewModel = new RegisterViewModel();
ViewBag.Roles = GetAllRolesAsSelectList();
return View(objRegisterViewModel);
}
The rest of the controller Action:
private List<SelectListItem> GetAllRolesAsSelectList()
{
List<SelectListItem> SelectRoleListItems =
new List<SelectListItem>();
var roleManager =
new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(new ApplicationDbContext()));
var colRoleSelectList = roleManager.Roles.OrderBy(x => x.Name).ToList();
foreach (var item in colRoleSelectList)
{
if (User.IsInRole("Administrator"))
{
SelectRoleListItems.Add(
new SelectListItem
{
Text = item.Name.ToString(),
Value = item.Name.ToString()
});
}
else
{
if (item.Name != "Administrator")
{
SelectRoleListItems.Add(
new SelectListItem
{
Text = item.Name.ToString(),
Value = item.Name.ToString()
});
}
}
}
return SelectRoleListItems;
}
Here is the View:
@Html.DropDownList("Role", (SelectList)ViewBag.Roles, "Select Role", new { @class = "form-control" })
Thanks for your help, any will be appreciated.
UPDATE: I tried changing this as follows:
ViewBag.Roles = context.Roles.Select(b => new SelectListItem { Value = b.Name, Text = b.Name });
Model:
[Required(ErrorMessage = "The Roles is required")]
public string Role { get; set; }
View:
@Html.DropDownListFor(m => m.Role, ViewBag.Roles as SelectList, "--Select Role--", new { @class = "form-control" })
Now getting an error System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Role'.'
Role is a string. I have tried using public IEnumerable<SelectListItem> UserRoles { get; set; }
And can get it to load but when I submit the form it errors that the Role is required. List is there and then disappears on submit. So it looses the selected value.
UPDATE:
I have followed this tutorial, it is what I originally used before. Asp net mvc 5
I am still getting this error: System.InvalidOperationException: 'The ViewData item that has the key 'UserRoles' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.'
Makes no sense I have used this before with no issues.
Solution 1:[1]
First, you need to add an Id to your Model Model will be like this
[Required(ErrorMessage = "The Roles is required")]
public string Role { get; set; }
public long Id {get; set;}
and then in Controller, you need to get the data from DB
List<Roles> roles = _context.Roles.ToList();
now we can make a ViewBag like this
ViewBag.ListOfRoles = new SelectList(roles, "Id", "Role");
After the in View, you have too many ways to display Select, but I prefer this way
<select asp-items="@ViewBag.ListOfRoles" asp-for="Id">
<option selected disabled>--Select--</option>
</select>
Note that asp-items
means the item to display in select
and asp-for
refers to the ModelVM
in your page, it must refer to an Id
to make sense or maybe it will be like something like this RoleId
I hope it's clear now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abdulrahma10 |