none
Adding Enum to MVC View breaks returned model RRS feed

  • Question

  • I have this controller:

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit(ExempKillData kill)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(kill).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index","Owners");
                }
                return View(kill);
            }

    and this (snipped-for-length) model:

    [Display(Name ="No Data")]
            [StringLength(40)]
            public string NO_DATA { get; set; }
    
            public DisposalMethods MethodOfDisposal { get; set; }
    
            public int ID { get; set; }

    and this (snipped-for-length) view:

                        <td valign="top">
                            @Html.EditorFor(model => kill.SPECIES, null, "SPECIES", new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => kill.SPECIES, "", new { @class = "text-danger" })
                        </td>
                        <td valign="top">
                            @Html.EnumDropDownListFor(model => kill.MethodOfDisposal, null, new { @class = "form-control" })
                        </td>
                        <td valign="top">
                            @Html.EditorFor(model => kill.EXEM_YEAR, null, "EXEM_YEAR", new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => kill.EXEM_YEAR, "", new { @class = "text-danger" })
                        </td>
    

    I have tried both of these methods for declaring the dropdown:

    
    @Html.EnumDropDownListFor(model => kill.MethodOfDisposal, "MethodOfDisposal", new { @class = "form-control" })
    
    @Html.EnumDropDownListFor(model => kill.MethodOfDisposal, null, new { @class = "form-control" })
    

    It works perfectly if I comment out the @Html.EnumDropDownListFor -- the model returned to the controller is fully detailed, except for the Enum value.

    Good model

    As soon as I uncomment the EnumDropDownList, the model returned to the controller is all null values. ...except the MethodOfDisposal.

    Null model

    ...this is despite my data looking good coming from the POST action on the view:

    Good data

    What am I doing wrong? I would expect adding a new field to the view to not break the rest of the model.

    Tuesday, June 25, 2019 4:19 PM

All replies