gog
gog

Reputation: 12988

How to do a dropdownlist using a model which contains a list of other model?

I need to create a DropDownList in my view which is using a specific model called Projects.

public class ProjectModel
{
    public string ProjectName { get; set; }
    public List<Company> Companies { get; set; }
}

I have a Company repository and I need to list those companies in a view that uses the ProjectModel class as @model.

Upvotes: 2

Views: 85

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56429

First off, you'll need a CompanyID in your project model (I'll assume it's an int). Secondly, you'll need a List<SelectListItem> that you can use for your Dropdown, so your model will look something like this:

public ProjectModel
{
    public string ProjectName { get; set; }
    public int CompanyID { get; set; }
    public List<Company> Companies { get; set; }
    public List<SelectListItem> CompaniesSelectList
    {
        get
        {
            return Companies
                .Select(c => new SelectListItem
                    {
                        Text = c.CompanyName,
                        Value = c.CompanyID.ToString(),
                        Selected = c.CompanyID == CompanyID
                    })
                .ToList();
        }
    }
}

Then in your view you can do:

@Html.DropdownListFor(m => m.CompanyID, Model.CompaniesSelectList, "Please Select")

Upvotes: 2

Related Questions