-1

为什么模型活页夹在编辑模式下的下拉列表中不起作用?

在编辑视图中,我编写了这段代码并测试了两个不同的 ddl:

@Html.DropDownList("ProductParentCategoryId", null, htmlAttributes: new { @class = "form-control" })
@Html.DropDownListFor(model => model.ProductParentCategoryId, (SelectList)ViewBag.ParentId)

在我的控制器中

ViewBag.ProductParentCategoryId = new SelectList(_productCategoryService.GetAllProductCategory(), "ProductCategoryId", "ProductCategoryTitle");
ViewBag.ParentId = new SelectList(_productCategoryService.GetAllProductCategory(), "ProductCategoryId", "ProductCategoryTitle");

但是编辑模式下的所有文本框都填充了模型活页夹,但下拉列表没有发生。

为什么 ? 在此处输入图像描述

- - - -更新 - - - -

我的意思是在编辑模式下,模型绑定器将数据库中的所有数据绑定到文本框和每个元素中......但在下拉列表中模型绑定器不会将数据库中的数据作为选定值绑定到下拉列表中

4

2 回答 2

0

我建议您绑定到视图模型而不使用 ViewBag。

但是要回答您的问题,在您的第一个示例中,您没有传递项目来填充下拉列表(第二个参数),而是传递了一个空值。

对于下拉列表,我一直使用 IEnumerable<SelectListItem>而不是 SelectList 集合。

因此,在您的视图模型中,您可以创建一个类似的属性:public IEnumerable<ProductCategory> ProductCategories {get; set;}并将其绑定到您的下拉列表,如下所示:

Html.DropDownListFor(m => m.ProductCategoryId, Model.ProductCategories)

https://msdn.microsoft.com/en-us/library/gg548304(v=vs.111).aspx

于 2017-02-20T20:50:13.913 回答
0

我找到了我的解决方案唯一应该在我的控制器中完成的事情:

[http Get]
    public ActionResult Edit(int id)
    {
        var selectedId = _productCategoryService.GetOneProductCategory(id);

        ViewBag.ProductParentCategoryId = new SelectList(_productCategoryService.GetAllProductCategory(), "ProductCategoryId", "ProductCategoryTitle", (int)selectedId.ProductParentCategoryId);
        ViewBag.GroupFiltersId = new SelectList(_groupFiltersService.GetAllGroupFilter().Where(a => a.GroupFilterParentId == null), "GroupFilterId", "GroupFilterTitle");
        return View(_productCategoryService.GetOneProductCategory(id));
    }

看法:

 @Html.DropDownList("ProductParentCategoryId", null, htmlAttributes: new { @class = "form-control" })
于 2017-02-21T10:43:11.803 回答