【问题标题】:set value of dropdownlist based on value from database in asp.net mvc5根据asp.net mvc5中数据库中的值设置下拉列表的值
【发布时间】: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


    【解决方案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 辅助方法将选择“运动”选项,假设您的视图被强类型化为YourViewModel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-30
      • 2017-05-26
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 2021-05-19
      相关资源
      最近更新 更多