[英]DropdownListfor to be auto selected on the basis of a value of string asp.net mvc
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
. 现在在我的控制器中,我在属性
_drinkType
获得值“ Milk”,“ tea”和“ coffee”。 I have to set the selected option in DropdownlistFor
when it matches with the property value 当它与属性值匹配时,我必须在
DropdownlistFor
设置所选选项
somewhat like if _drinktype = milk
then dropdownlistFor will be loaded automatically with Milk selected 有点像
if _drinktype = milk
那么dropdownlistFor将在选择Milk的情况下自动加载
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. 您可以使用控制器中的可能选项设置
ViewBag
属性,并且模型只能保留将保留实际值的属性。 In your controller, add the value to 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"}
};
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: 编辑 :由于您具有
Text
属性,并且如果SelectedListItem
的Value
中存在匹配项,则将选择selected选项,您可以在模型中添加一个属性:
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
: 从控制器操作结果返回视图之前,必须基于
_drinkTypeValue
的值设置_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
: 在您的视图中,将下拉值绑定到
_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. 当用户提交表单时,它实际上将提交
_drinkTypeValue
因此您将不得不以类似的方式再次将其转换为_drinkType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.