DropdownListfor to be auto selected on the basis of a value of string asp.net mvc

删除回忆录丶 提交于 2019-12-12 02:38:45

问题


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.



来源:https://stackoverflow.com/questions/43518802/dropdownlistfor-to-be-auto-selected-on-the-basis-of-a-value-of-string-asp-net-mv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!