samedi 25 avril 2015

C# MVC5 @Html.EnumDropDownListFor loses selection on "postback"


MVC5 EF6

I have a Product. A product can have multiple Titles, A title has a Type which is an Enum.

I am working on the Create View for a Product - The Model is the Product

View:

            @for (int x = 0; x < Model.ProdTitles.Count; x++)
            {                    
                <tr>
                    <td>
                        @Html.TextBoxFor(model => model.ProdTitles.ToArray()[x].Title, new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.ProdTitles.ToArray()[x].Title, "", new { @class = "text-danger" })
                    </td>
                    <td>
                        @Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].TitleTypeID, new { @class = "form-control" })
                    </td>
                    <td>
                        @Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].CultureID, new { @class = "form-control" })
                    </td>
                </tr>
            }

In the Controller - when I create a product to return to the view, I create one title for each title type and add it to the product. The view displays everything as I expect.

Working as required

When I hit the Create button, the product and the titles are returned to the controller as expected and I validate the titles (different validation depending on the type). I add any errors to the ModelState and therefore, ModelState.IsValid is false.

I return back to the View return View(product); Debugging this product, all the titles are in the product and they all still have their correct types but the View now displays the first Enum in the list, for all titles and not the one that is actually in the model!

Showing first enum for all titles

If I change the EnumDropDown to a text box, the correct type is displayed, so the model is definitely correct:

proves model has the correct type

I'm not sure why this is happening and I hope someone can suggest a fix? Is it a bug in the C:\Users\Rick\Desktop\C.png? or am I doing something wrong?


Aucun commentaire:

Enregistrer un commentaire