Joshua
Joshua

Reputation: 490

Help with MVC3 Html.DropDownListFor

I need some help with how to use the Html.DropDownListFor in MVC3 since the documentation is just crazy bad and I'm not finding the answer I need on here.

I have the following models

public class Users
{
     public virtual User_Roles RoleID {get; set;}
     public virtual string UserName{get; set;}
     ... more stuff
}

public class User_Roles
{
    public virtual Int32 RoleID {get; set;}
    public virtual string Role {get; set;}
}

My page (create_user.cshtml) looks like this:

@model Users
... stuff
@Html.LabelFor(m => m.RoleID)
@Html.DropDownListFor(m => m.RoleID, Model.RoleID.Role, Model.RoleID.RoleID)

It keeps throwing the error "'System.Web.Mvc.HtmlHelper<Users>' does not contain a definition for 'DropDownListFor'"

Can anyone explain to me how I can pull the list of role names and IDs from the DB since this clearly is not the way to do it?

Upvotes: 0

Views: 948

Answers (1)

Charandeep Singh
Charandeep Singh

Reputation: 972

You need to pass items of dropdown using SelectList.

Make sure you retrieve Roles in ViewBag.Roles from controller.

@Html.DropDownListFor(m => m.RoleId, new SelectList(ViewBag.Roles as System.Collections.IEnumerable, "Id", "Name"), "")

Upvotes: 2

Related Questions