ASP.Net MVC Dynamic DropDownList - how to create one

10,597
@model ebs.Models.RatesList
@{ Layout = null; }
<tr>
    <td>
        @Html.TextBoxFor(modelItem => modelItem.TypeID)
    </td>
    <td>
        @Html.DropDownList(
            "NumSelected", 
            Enumerable
                .Range(0, Model.TypeCount)
                .Select(x => new SelectListItem 
                { 
                    Value = x.ToString(), 
                    Text = x.ToString() 
                })
        )
    </td>
</tr>

But obviously it would be much better to define this as part of your view model:

public class RatesList
{
    public int NumSelected { get; set; }
    public IEnumerable<SelectListItem> Values
    {
        get 
        {
            return Enumerable
                .Range(0, this.TypeCount)
                .Select(x => new SelectListItem 
                { 
                    Value = x.ToString(), 
                    Text = x.ToString() 
                })        
        }
    }

    ... some other properties
}

and then in your view you would simply bind the dropdown to the corresponding properties of your view model:

@model ebs.Models.RatesList
@{ Layout = null; }
<tr>
    <td>
        @Html.TextBoxFor(modelItem => modelItem.TypeID)
    </td>
    <td>
        @Html.DropDownListFor(modelType => modellType.NumSelected, Model.Values)
    </td>
</tr>
Share:
10,597
Mark
Author by

Mark

Updated on June 05, 2022

Comments

  • Mark
    Mark almost 2 years

    I am using an Editor template - as I need to loop through my model, and display/edit many of the RatesList objects in my model.

    This ensures the ID and Name are correct - so they bind back to my model on Post back to the controller.

    However the drop down list, needs to be dynamic - so has to show from 0 to whatever my Model.TypeCount is.

    Is there anyway of me using the @Html.DropDownListFor helper - so that the drop down list is named correctly? In my code below, it is just a select statement - as I don't know how to make the drop down list dynamic - but then the naming convention isn't used, and the drop down list is not binding back to my model. My Editor View is:

    @model ebs.Models.RatesList
    @{ Layout = null; }
    <tr>
    <td>
        @Html.TextBoxFor(modelItem => modelItem.TypeID)
    </td>
    <td>
        @{ var num = Model.TypeCount; }
    
        <select id="NumSelected" name="NumSelected">
            @for (var i = 0; i <= num; i++)
            {
                <option value="@i">@i</option>
            }
        </select>
    </td>
    </tr>
    

    Thanks for any help,

    Mark

  • Mark
    Mark about 10 years
    Once again Darin - you've so eloquently coded a solution to a problem. Thanks a lot - I'll mark as the answer when stack overflow allows. Cheers, Mark