Search code examples
c#asp.net-mvclinqdropdownlistfor

Passing DropDownListFor through Model Class


I can't seem to crack how to pass a DropDownListFor through my Model class, I've only been able to figure how to do it just using a standard dropdownlist. I'm gonna post how I've done it in the past

 public class NewLogin
{
    public string UserRole     { get; set; }
    public int RoleID          { get; set; }
    public SelectList RoleList { get; set; }
}

Here's how I'm getting the data for my DDL in my LinQ statement, Is there a more efficient way of doing this?

    public NewLogin PopUserDDL()
    { 
        NewLogin nl = new NewLogin();
        using (database db = new database())
        {                                     
            nl.RoleList = new SelectList(GetRolesForDDL(), "RoleID", "UserRole");                
        }
        return nl;      
    }   
    public  List<NewLogin> GetRolesForDDL()
    {
        using (database db = new database())
        {
            return (from r in db.UserRole                       
                    select new NewLogin
                    {
                        UserRole = r.Role,
                        RoleID = r.RoleID
                    }).ToList();
        }
    }

I'm calling it in my view like
@Html.DropDownList("lstRoles",(SelectList)ViewBag.RolesList)

And I'm passing it like

  public ActionResult Index(NewLogin newlogin, int lstRoles)
    {
    }

I've tried dropdown for and trying to get it passed straight through the model but haven't had any luck. Thanks


Solution

  • Html.DropDownListFor requires that your view is strongly typed. If your model is of type NewLogin, you can write it like this :

    @model MyNamespace.NewLogin
    
    @Html.DropDownListFor(model => model.RoleID, Model.RoleList)
    

    In your post action, you get selected RoleID in your NewLogin parameter.

    Edit : in your controller, your calling action can be this :

    public ActionResult Index()
    {
        NewLogin newLogin = PopUserDDL();
        return View(newLogin);
    }
    

    Model property of your view will contain the data you need. It is a better solution than ViewBags.