Search code examples
asp.net-mvcrazorrazor-declarative-helpers

Convert Select to DropDownListFor MVC 5


I have this select and I'm needing to convert it to a DropDownlistFor call.

Can anyone help out:

<select class="form-control" name="QuestionBasicSection.Questions[@counter].ANSWER_LOOKUP_OPTION_ID" id="@selectId">
    @foreach (var x in questionBasicSection.Questions[j].LookupGroup)
    {
        <option value="@x.Value" selected="@x.Selected">@x.Text</option>
    }
</select>

Here is a skeleton, I'm just not sure how to setup the SelectList and the Selected Value

@Html.DropDownListFor(q => questionBasicSection.Questions[@counter].ANSWER_LOOKUP_OPTION_ID, 
             new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red"  },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"}
                    },
                  "value",
                  "text",
                   // Not sure how to set selected 
           )

Solution

  • DropDownListFor works by providing the source/destination property as the first parameter, and the array of options as the second parameter. In your example:

    questionBasicSection.Questions[@counter].ANSWER_LOOKUP_OPTION_ID

    That property on your model should contain the initial value you wish the DropDownList to be set to. For example, if you wish your DropDownList to display 'Blue' on page load, set the value of ANSWER_LOOKUP_OPTION_ID to 2 in your controller (or wherever the Model is created).