Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5modelbinder

asp.net mvc model binder does not work for drop down list in edit mode


why model binder does not work on drop down list in edit mode ?

in edit view i write this code and test two different ddl :

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

and in my controller

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

but all textbox in edit mode fill with model binder but not happening for drop down list.

why ? enter image description here

-------UpDate-------

I mean is in edit mode, model binder bind all data from database in textbox and each elements ... but in dropdownlist model binder does not bind data from database as Selected Value into dropdownlist


Solution

  • i find my solution The only thing that should be done in my controller:

    [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));
        }
    

    view:

     @Html.DropDownList("ProductParentCategoryId", null, htmlAttributes: new { @class = "form-control" })