/ / asp.net mvcモデルバインダーが編集モードのドロップダウンリストで機能しない-c#、asp.net、asp.net-mvc、asp.net-mvc-5、modelbinder

asp.net mvcモデルバインダーは、ドロップダウンリストの編集モードでは機能しません - c#、asp.net、asp.net-mvc、asp.net-mvc-5、modelbinder

編集モードのドロップダウンリストでモデルバインダーが機能しないのはなぜですか?

編集ビューでこのコードを記述し、2つの異なる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");

ただし、編集モードのすべてのテキストボックスはモデルバインダーで塗りつぶされますが、ドロップダウンリストでは発生しません。

どうして ? ここに画像の説明を入力

- - - -更新 - - - -

つまり、編集モードでは、モデルバインダーはテキストボックス内のデータベースからのすべてのデータと各要素をバインドします... しかし、ドロップダウンリストモデルでは、バインダーはデータベースからのデータをバインドしません 選択した値 ドロップダウンリストに

回答:

回答№1は0

ViewBagを使用せず、ビューモデルにバインドすることをお勧めします。

しかし、質問に答えるために、最初の例では、アイテムを渡してドロップダウン(2番目のパラメーター)を設定しませんでしたが、代わりにnull値を渡しました。

また、私はいつも使用しているドロップダウンのために 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


回答№2の場合は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" })