[英]set value of dropdownlist based on value from database in asp.net mvc5
I have declared a SelectListItem object in my controller, I able to populate them into my DropDownList in Create() page, however I am having problem trying to get value from model to set the selected value of the DropDownList in Edit() page. 我已经在控制器中声明了SelectListItem对象,可以将它们填充到Create()页面的DropDownList中,但是尝试从模型获取值以设置Edit()页面中DropDownList的选定值时遇到问题。
Code of Create() in controller: 控制器中的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();
}
I am able to populate the DropDownList in Create() view page using all the Viewbag(s). 我可以使用所有Viewbag在Create()视图页面中填充DropDownList。
However now I wished to populate the DropDownList in Edit() view page at the same time set selected value from the model. 但是,现在我希望同时在Edit()视图页面中填充DropDownList,同时设置从模型中选择的值。
Below are the codes from Edit() view page: 以下是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>
All you need to do is to set the category
property value of your view model object in your Edit action method. 您需要做的就是在“编辑”操作方法中设置视图模型对象的
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);
}
Now the DropDownListFor
helper method will make the option "Sport" selected, assuming your view is strongly typed to YourViewModel
现在,
DropDownListFor
helper方法将使选项“ Sport”处于选中状态,假设您的视图已强类型YourViewModel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.