-->

DropdownListfor to be auto selected on the basis o

2019-09-17 11:31发布

问题:

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

回答1:

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 to ViewBag:

ViewBag.DrinkTypeDropDown = new List<SelectListItem>()
{
    new SelectListItem{Text="Milk", Value="1"},
    new SelectListItem{Text="coffee", Value="2"},
    new SelectListItem{Text="tea", Value="3"}
};

In your, declare the drop down list:

@Html.DropDownListFor(model => model._drinkType, (IEnumerable<SelectListItem>)ViewBag.DrinkTypeDropDown)

Edit: Since you have the Text property and the selected option will be selected if there is a match in the Value of SelectedListItem, you could add a property in your model:

public string _drinkTypeValue { get; set; }

Before returning the view from the controller action result, you would have to set the _drinkTypeValue based on the value of _drinkType:

model._drinkTypeValue = model._drinkTypeDropDown.Where(item => item.Text == model._drinkType).FirstOrDefault().Value; // You will have to treat null values of FirstOrDefault() here

In your view, bind the drop down value to the _drinkTypeValue:

@Html.DropDownListFor(model => model._drinkTypeValue, Model._drinkTypeDropDown)

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.