【发布时间】:2017-03-16 15:39:59
【问题描述】:
我已经在我的控制器中声明了一个 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(s) 在 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>
【问题讨论】:
标签: c# asp.net-mvc html.dropdownlistfor populate selectedvalue