[英]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.