I am using entity framework passing in a many to many relationship of "Role" into my controller.
In my controller, I have set:
public ActionResult New()
{
var db = new MyContext();
return View(new UsersNew
{
(from item in db.Roles
select item).Select(role => new RoleCheckbox
{
Id = role.Id,
IsChecked = false,
Name = role.Name
}).ToList()
});
My Viewmodel contains 2 classes:
public class RoleCheckbox
{
public int Id { get; set; }
public bool IsChecked { get; set; }
public string Name { get; set; }
}
public class UsersNew
{
public IList<RoleCheckbox> Roles { get; set;}
[Required, MaxLength(128)]
public string Username { get; set; }
[Required, DataType(DataType.Password)]
public string Password { get; set; }
[Required, MaxLength(128), DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
I have a strongly typed view from my UsersNew class in my ViewModel:
<ul class="list-group">
@for (int i = 0; i < Model.Roles.Count; i++)
{
<li class="list-group-item">
@Html.Hidden("Roles[" + i + "].Id"), Model.Roles[i].Id)
<label for="Roles_@(i)__IsChecked">
@Html.CheckBox("Roles[" + i + "].IsChecked", Model.Roles[i].IsChecked)
@Model.Roles[i].Name
</label>
</li>
}
</ul>
However, in my controller I have error stating:
"Error 1 Cannot initialize type 'myBlog.Areas.Admin.ViewModels.UsersNew' with a collection initializer because it does not implement 'System.Collections.IEnumerable "
I have also tried this in my controller:
using (var db = new MyContext())
var Roles = MyBlog.Roles.Select(role => new RoleCheckbox
{
Id = role.Id,
IsChecked = false,
Name = role.Name
}).ToList();
return View(new UsersNew { Roles });
I could be doing this wrong, but how can I pass in my list of Roles from my database to my view, so that I can display a checkbox of role "Admin", "Moderator", and "User" on my user creation view?
Thank you