I have one string and one list proeprty in my model
public string _drinkType { get; set; }
public List<SelectListItem> _drinkTypeDropDown { get; set; }
in my view
@Html.DropDownListFor(m => m._drinkTypeDropDown , new List<SelectListItem>
{
new SelectListItem{Text="Milk", Value="1"},
new SelectListItem{Text="coffee", Value="2"},
new SelectListItem{Text="tea", Value="3"}
}
Now in my controller , I am getting the the value "Milk" , "tea" and "coffee" in the property _drinkType
. I have to set the selected option in DropdownlistFor
when it matches with the property value
somewhat like
if _drinktype = milk
then dropdownlistFor will be loaded automatically with Milk selected
You can set a
ViewBag
property with the possible options in the controller and the model can keep only the property which will hold the actual value. In your controller, add the value toViewBag
:In your, declare the drop down list:
Edit: Since you have the
Text
property and the selected option will be selected if there is a match in theValue
ofSelectedListItem
, you could add a property in your model:Before returning the view from the controller action result, you would have to set the
_drinkTypeValue
based on the value of_drinkType
:In your view, bind the drop down value to the
_drinkTypeValue
:When the user submits the form, it will actually submit the
_drinkTypeValue
so you will have to convert it again to_drinkType
in a similar fashion.