1
@Html.DropDownListFor(m => m.field, Model.fieldList, "Select")

I have the code above to get the values of a drop down list from a database. Because the database does not have the select value, I am add it to the list. However, I want to set the selected value to a certain value(variable). How can I do this?

Say I want the selected value to be "WI" and "WI" is in the list. How do i do this? Or how do I specify the @value property?

1 Answer 1

0

The DropDownListFor function will first look if there is a selected value in the provided select list. If there are no selected values in the selected list items, it will look at the value of the field that the drop down list is for and attempt to match that to the value of each select list item until it finds the correct one. If any select list item does not have value, it will compare it to the text instead.

Once you have the full list generated, loop through it and find the value you want selected, then set the selected property to true and it should choose that one.

Sign up to request clarification or add additional context in comments.

4 Comments

I am able to do this when the format of the @html.dropdownlistfor as different as mentioned here: stackoverflow.com/a/13713621/807223 How do I do this with this format
To me that seems like your answer. If that's not it, I don't understand what you are asking
How do I specify the @value attribute? Say I want the selected value to be "WI" and "WI" is in the list?
It has to be in the list for it to be selected. You need to add WI to the list and then you can set it as the selected value. If you don't want to add it to the list, you need to give a more complete specification for exactly what you want to happen.

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.