Fırat Lokman
Fırat Lokman

Reputation: 3

Mvc 5 Multiselectlist selected not working

select element created with items in it, but "selected" properties not showing in html result. What i do wrong?

this code is working:

controller:

ViewBag.ProductTwistDirectionID = new SelectList(db.tblProductTwistDirection, 
       "ProductTwistDirectionID", 
       "ProductTwistDirectionName", 
        tblProduct.ProductTwistDirectionID);

view:

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

this code is not working: (selected items not selecting at render)

controller:

ViewBag.ProductUsePurposes = new MultiSelectList(db.tblProductUsePurpose,
                                                 "ProductUsePurposeID",
                                                 "ProductUsePurposeName",
                                                 tblProduct.ProductUsePurposes
                                                 .Select(x 
                                                         => x.ProductUsePurposeID)
                                                 .ToArray());

view:

@Html.DropDownListFor(model => model.ProductUsePurposes, 
                      null, 
                      new 
                         { 
                           @class = "chosen-select", 
                           multiple = "multiple", 
                           data_placeholder = "Choose use purposes", 
                           style = "width: 400px;" 
                          })

Upvotes: 0

Views: 998

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Your ViewBag member holding the select list cannot be named the same as your model property. ViewBag is used, in addition to ViewData and Request, to compose the ModelState object and whatever is in ModelState overrides the properties on your model.

Simply, you need to rename ViewBag.ProductUsePurposes to something like ViewBag.ProductUsePurposesChoices. Then, you should be fine.

Upvotes: 2

Related Questions