2

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

1 Answer 1

6
@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>
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.