2017-02-20 30 views
-1

爲什麼模型綁定器在編輯模式的下拉列表中不起作用?asp.net mvc模型綁定器在編輯模式下不能用於下拉列表

在編輯視圖我寫這篇文章的代碼和測試兩種不同的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"); 

但在編輯模式下,所有的文本框填充模型綁定,但不會發生了下降下拉列表。

爲什麼? enter image description here

------- -------更新

我的意思是在編輯模式下,模型綁定綁定從數據庫中的所有文本數據和各元素... 但在下拉列表模型綁定不從數據庫選定值將數據綁定到下拉列表

回答

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" }) 
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

相關問題