Asp.net mvc ModelState valid when using dropdownlist

ModelState.IsValid always false, because I use the drop-down list in the form I want to submit, and get this exception:

The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types


Model:

public class NewEmployeeModel
{
    [Required(ErrorMessage = "*")]
    [Display(Name = "Blood Group")]
    public IEnumerable<SelectListItem> BloodGroup { get; set; }
}

View:

<div class="form-group">
   @Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
   <div class="col-md-4">        
      @Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroup, "Please Select", new { @class = "form-control" })
   </div>
</div>

Controller:

 [HttpPost]
    public ActionResult Employee(NewEmployeeModel model)
    {
        var errors = ModelState
            .Where(x => x.Value.Errors.Count > 0)
            .Select(x => new { x.Key, x.Value.Errors })
            .ToArray();

        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("Employee", "Model is Not Valid");
            return View("Employee", model);
        }
        else
        {
            return null;
        }
    }
+4
source share
1 answer

This is not how you use SelectList

You need another property of the model to hold the selected BloodGroup value:

public class NewEmployeeModel
{
    [Required(ErrorMessage = "*")]
    [Display(Name = "Blood Group")]
    public int BloodGroup { get; set; }

    public IEnumerable<SelectListItem> BloodGroups { get; set; }
}

<div class="form-group">
   @Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
   <div class="col-md-4">        
      @Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroups, "Please Select", new { @class = "form-control" })
   </div>
</div>

You do not publish all the items in the drop-down list, you publish only the value of the selected item. In my example, I assume this is an int (possibly a primary key value).

If validation fails in POST, you need to populate these values ​​again:

if (!ModelState.IsValid)
{
    model.BloodGroups = GetBloodGroups();

    ModelState.AddModelError("Employee", "Model is Not Valid");
    return View("Employee", model);
}
+6

All Articles