根据 asp.net mvc5 中数据库的值设置下拉列表的值

set value of dropdownlist based on value from database in asp.net mvc5

我已经在我的控制器中声明了一个 SelectListItem 对象,我可以在 Create() 页面中将它们填充到我的 DropDownList 中,但是我在尝试从模型中获取值以在编辑中设置 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>

您需要做的就是在 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 辅助方法将使选项 "Sport" 处于选中状态,假设您的视图被强类型化为 YourViewModel