CesarCarrillo
CesarCarrillo

Reputation: 157

Get dropdownlist selected option from C# list of objects

I have an list of objects that I receive in my Razor View in C#

 @model IEnumerable<Project.Models.EvaluationObject>

In each object of the IEnumerable I have a property called "MaxValue" that I want to put selected in a input select of html.

  foreach(var item in Model){
        <select>
            <option value=1>One</option>
            <option value=2>Two</option>
            <option value=3>Three</option>
            <option value=4>Four</option>
        </select>

  }

For each item I want to build a select input with the value of the item.MaxValue selected

i.e. In the first loop item.MaxValue = 3, then I should build the next select:

       <select>
            <option value=1>One</option>
            <option value=2>Two</option>
            <option value=3 selected="selected">Three</option>
            <option value=4>Four</option>
        </select>

The item.MaxValue is ever between 1 and 4, so If the value is 3 the selected value in the select input is 3.

The First solution I had, is to put an if statement in each option, but I think that's impractrical:

 foreach(var item in Model){
    <select>
        <option value=1 @if(item.MaxValue==1){<text>selected="selected"</text>})>One</option>
        <option value=2 @if(item.MaxValue==2){<text>selected="selected"</text>}>Two</option>
        <option value=3 @if(item.MaxValue==3){<text>selected="selected"</text>}>Three</option>
        <option value=4 @if(item.MaxValue==4){<text>selected="selected"</text>}>Four</option>
    </select>

 }

Hope you can help me, May be I should use some JavaScript.

Upvotes: 0

Views: 1341

Answers (1)

Luke Hutton
Luke Hutton

Reputation: 10722

You can add a IEnumerable<SelectListItem> to your model:

Model:

public class EvaluationObject
{
    public IEnumerable<SelectListItem> EvaluationList
    {
        get
        {
            return Enumerable.Range(1, 4)
                             .Select(x => new SelectListItem
                                 {
                                     Selected = x == MaxValue,
                                     Text = NumberToWord(x),
                                     Value = x
                                 });
        }
    }

    public int MaxValue { get; set; }

    public int EvaluationNumber { get; set; }
}

View:

foreach (var item in Model) 
{
    @Html.DropDownListFor(x => x.EvaluationNumber, item.EvaluationList)
}

Upvotes: 1

Related Questions