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

Viewed 6558

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))
1 Answers
Related