I have a basic form allowing users to input details which then gets posted and saved to a database - this works as expected without any issues:

@model R32.Register.Models.RegisterCar
    ViewBag.Title = "Edit Your R32";

<h2>Edit R32</h2>
    @using (Html.BeginForm("UpdateCar", "Garage", FormMethod.Post))
            <legend>Enter details</legend>
                    @Html.LabelFor(m => m.NumberPlate)
                    @Html.EditorFor(m => m.NumberPlate, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.NumberPlate)
                    @Html.LabelFor(m => m.Edition)
                    @Html.EnumDropDownListFor(m => m.Edition, "Select an edition:", new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Edition)
                    @Html.LabelFor(m => m.Colour)
                    @Html.EnumDropDownListFor(m => m.Colour, "Select a colour:", new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Colour)
            <input type="submit" value="Save Changes" />

Model snippet:

public MkEnum? Edition { get; set; }


public enum MkEnum
    Mk4 = 1,
    Mk5 = 2

The control renders as expected, with the Edition dropdownlist having three values: "Select an edition", "Mk4", and "Mk5".

The user is able to select an edition, control is validated, then posted to the controller.

The Post is successful, and all selected values are sent to the controller - the app then persists the data in a database, and so on, without any problems.

The issue is when I pass this model back into the same View to allow the user to edit the saved data, the saved values for the enums are NOT being set as the selected value in the dropdownlist.

I can confirm that any saved string values, such as NumberPlate in this example, are being passed back into the view and loaded into the UI.

Putting a breakpoint on the viewmodel as it renders I can confirm that my @model contains the saved values for enum properties - Edition for example - but the end result is that the "Select an edition:" dropdown list is rendered containing the expected dropdown values, but it's value is the default "Select an edition:" instead of the actual value passed in via. m.Edition.

I have been able to get this working using DropDownListFor - but am having difficulties in understanding why this is not working using EnumDropDownListFor, as this clearly seems like a more elegant solution.

Does anyone have any help/advice for this?

Related posts

Recent Viewed