Search code examples
c#asp.net-mvcdropdownlistfor

Populate Drop Down List from IEnumerable in the Model, Set Selected Value


This is the model:

public class PolicyDetail
{
    public Policy Policy { get; set; }
    public IEnumerable<Insured> Insured { get; set; }
    public IEnumerable<Risk> Risk { get; set; }
    public IEnumerable<Construction> Construction { get; set; }
}

Construction just looks like this:

public class Construction
{
    public int ConstructionID { get; set; }
    public string ConstructionType { get; set; }
}

And in the DB, there are only 4 rows. It's basically an enum.

And within Risk is this property:

public int ConstructionID { get; set; }

Before sending the model to the view, we fill up each object within PolicyDetail, where Insured and Risk are children of Policy. Construction is loaded up every time with all four of it's rows.

So, in the model, we are listing off all the Risks. And as we display them, we want to show Constructions as a dropdown list, and set the selected value to whatever is the value in Risk.ConstructionID.

It's amazing how much heart burn these simple dropdowns can be in MVC.

@foreach (var item in Model.Risk)
{
    ... Other items in Risk

    <div class="form-group">
        @Html.Label("Construction Type", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList(?????????)
        </div>
    </div>

    ... Other items in Risk
}

How do I fill up that drop down with all of the items from

Model.Constrution

and set the selected item to what's in

item.ConstrucitonID

?

Thanks!

EDIT:

Here's the working solution:

@Html.DropDownList("ConstructionType", new SelectList(Model.Construction.Distinct().ToList(), "ConstructionID", "ConstructionType", item.ConstructionID))

Solution

  • You need to convert the IEnumerable<Construction> to SelectList and specify the selected value.

    Something like the following (note: I did not code this in VS, so syntax or parameters are probably not correct, but you'll get the idea)

    @Html.DropDownList("ddlConstructionId", new SelectList(Model.Constrution, "ConstructionID" , "ConstructionType", item.ConstrucitonID))
    

    You'll need to specify the selected value when creating the SelectList. I think this is the best constructor for you:

    public SelectList(
        IEnumerable items,
        string dataValueField,
        string dataTextField,
        object selectedValue
    )
    

    So, in your case, it would be:

    @Html.DropDownList("CompanyName",
                   new SelectList(Model.Construction.Distinct().ToList(), "ConstructionID", "ConstructionType", item.ConstrucitonID));