[英]DropdownListfor to be auto selected on the basis of a value of string asp.net mvc
我的模型中有一个字符串和一个列表属性
public string _drinkType { get; set; }
public List<SelectListItem> _drinkTypeDropDown { get; set; }
在我看来
@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"}
}
现在在我的控制器中,我在属性_drinkType
获得值“ Milk”,“ tea”和“ coffee”。 当它与属性值匹配时,我必须在DropdownlistFor
设置所选选项
有点像if _drinktype = milk
那么dropdownlistFor将在选择Milk的情况下自动加载
您可以使用控制器中的可能选项设置ViewBag
属性,并且模型只能保留将保留实际值的属性。 在您的控制器中,将值添加到ViewBag
:
ViewBag.DrinkTypeDropDown = new List<SelectListItem>()
{
new SelectListItem{Text="Milk", Value="1"},
new SelectListItem{Text="coffee", Value="2"},
new SelectListItem{Text="tea", Value="3"}
};
在您的列表中,声明下拉列表:
@Html.DropDownListFor(model => model._drinkType, (IEnumerable<SelectListItem>)ViewBag.DrinkTypeDropDown)
编辑 :由于您具有Text
属性,并且如果SelectedListItem
的Value
中存在匹配项,则将选择selected选项,您可以在模型中添加一个属性:
public string _drinkTypeValue { get; set; }
从控制器操作结果返回视图之前,必须基于_drinkTypeValue
的值设置_drinkType
:
model._drinkTypeValue = model._drinkTypeDropDown.Where(item => item.Text == model._drinkType).FirstOrDefault().Value; // You will have to treat null values of FirstOrDefault() here
在您的视图中,将下拉值绑定到_drinkTypeValue
:
@Html.DropDownListFor(model => model._drinkTypeValue, Model._drinkTypeDropDown)
当用户提交表单时,它实际上将提交_drinkTypeValue
因此您将不得不以类似的方式再次将其转换为_drinkType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.