Reputation: 87
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?
Upvotes: 0
Views: 10605
Reputation:
Do like this:
ViewBag.cityid = new SelectList(db.hr_pr_cities, "CityID", "Name");
and in view like this:
@Html.DropDownList("cityid", null, "Select City", null)
Upvotes: 1
Reputation: 17182
Problem is with the below code -
public ActionResult Index(string RoleName, string UserName)
{
SelectList list = new SelectList(Roles.GetAllRoles());
ViewBag.Roles = list;
return View();
}
In above code you never initiated - ViewBag.UserName
, but your view is expecting UserName property in ViewBag (you only initiated Roles). you initiate it and problem will be done.
Upvotes: 1
Reputation: 101701
type of items is List<SelectListItem>
, not SelectList
.Try:
ViewBag.UserName as List<SelectListItem>
Upvotes: 0
Reputation: 6366
Try this:
@model IEnumerable<UserProfile>
@Html.DropDownList("UserName",new SelectList(ViewBag.UserName, "Value", "Text"))
Or change the type of your UserName
to SelectList
and then modify it here:
ViewBag.UserName = new SelectList(items, "Value", "Text");
//instead of ViewBag.UserName = items;
Upvotes: 0