Ok so here is my problem. I’m trying to populate an @Html.DropDownListFor() with my Roles minus the Admin Role. This works just fine, but it shows all roles:
@Html.DropDownListFor(m => m.RoleName, new SelectList(Roles.GetAllRoles()))
However this shows all roles including the Admin roll.
So I have created another class UserHelper.cs with this Method that is basicly the same thing as Roles.GetAllRoles():
public string[] GetUserRoles()
{
string[] userroles = null;
using (MainVeinDataDataContext conn = new MainVeinDataDataContext())
{
userroles = (from r in conn.Roles
where r.Rolename != "Admin"
select r.Rolename).ToArray();
}
return userroles;
}
However, being very new to MVC, I have no idea how to expose this Method to the DropDownList in the view. So this doesn’t work no matter what I try:
@Html.DropDownListFor(m => m.RoleName, new SelectList(GetUserRoles()))
I’m not sure what I am missing and it is driving me crazy. Hopefully someone out there knows what I’m missing.
A view should not be responsible for pulling data from some datasources. It should only be responsible for manipulating the data that it was passed by the controller under the form of a vie model.
What you are trying to do is an anti-MVC pattern. The code that you have put in this
GetUserRolesmethod is the controller (or a data access layer) responsibility and the result of it it should be part of your view model. So for example you would have the following view model:and then you will have a controller action which will populate this view model:
and now in your view: