[英]Passing value from database to view in DropDownList in ASP.net mvc 4
[英]set value of dropdownlist based on value from database in asp.net mvc5
我已經在控制器中聲明了SelectListItem對象,可以將它們填充到Create()頁面的DropDownList中,但是嘗試從模型獲取值以設置Edit()頁面中DropDownList的選定值時遇到問題。
控制器中的Create()代碼:
public ActionResult Create()
{
var tagList = new List<SelectListItem>();
tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
tagList.Add(new SelectListItem() { Text = "Promo", Value = "Promo" });
tagList.Add(new SelectListItem() { Text = "Limited", Value = "Limited" });
tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
tagList.Add(new SelectListItem() { Text = "New", Value = "New" });
var catList = new List<SelectListItem>();
catList.Add(new SelectListItem() { Text = "Men", Value = "Men" });
catList.Add(new SelectListItem() { Text = "Women", Value = "Women" });
catList.Add(new SelectListItem() { Text = "Sport", Value = "Sport" });
catList.Add(new SelectListItem() { Text = "Casual", Value = "Casual" });
var statusList = new List<SelectListItem>();
statusList.Add(new SelectListItem() { Text = "Available", Value = "Available" });
statusList.Add(new SelectListItem() { Text = "Unavailable", Value = "Unavailable" });
ViewBag.tagDropDown = tagList;
ViewBag.catDropDown = catList;
ViewBag.statusDropDown = statusList;
return View();
}
我可以使用所有Viewbag在Create()視圖頁面中填充DropDownList。
但是,現在我希望同時在Edit()視圖頁面中填充DropDownList,同時設置從模型中選擇的值。
以下是Edit()視圖頁面中的代碼:
<div class="form-group">
@Html.LabelFor(model => model.category, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.category, new SelectList(ViewBag.catDropDown, "value", "text"), htmlAttributes: new { @class = "form-control" })
</div>
</div>
您需要做的就是在“編輯”操作方法中設置視圖模型對象的category
屬性值。
public ActionResult Edit(int id)
{
var vm=new YourViewModel();
vm.category="Sport"; // Replace this hard coded value with value from db
// to do : Load ViewBag.catDropDown
return View(vm);
}
現在, DropDownListFor
helper方法將使選項“ Sport”處於選中狀態,假設您的視圖已強類型YourViewModel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.