我已经在我的控制器中声明了一个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,同时从模型中设置所选值。
以下是编辑()视图页面中的代码:
<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>
答案 0 :(得分:1)
您需要做的就是在Edit操作方法中设置视图模型对象的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
辅助方法将选择&#34; Sport&#34;选中,假设您的视图被强类型为YourViewModel