0

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.

1 Answer 1

1

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

Comments

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.