Invalid ModelState with a bound DropDownList

I had a simple model, like so:

    public class AmusementPark {
        public List<SelectListItem> Coasters { get; set; }

I bound this simple model to a simple DropDownList, like so:

@Html.DropDownListFor(model => model.Coasters, Model.Coasters)

But when I submitted my model to the controller, I received an invalid ModelState. So I looked through the various errors in the ModelState with a bit of code:

    var errors = ModelState
        .Where(err => err.Value.Errors.Count > 0)
        .Select(err => new { err.Key, err.Value.Errors })

Lurking in the ModelState errors wasthis wonderful System.InvalidOperationException exception:

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

Returning to the line in question, a DropDownList bound to a List of SelectListItem objects:

@Html.DropDownListFor(model => model.Coasters, Model.Coasters)

To resolve it, I first modified my model to have a key value:

    public class AmusementPark {
        public string CoasterId { get; set; }
        public List<SelectListItem> Coasters { get; set; }

Then I modified the view to set the new CoasterId as the first parameter in my DropDownListFor helper:

@Html.DropDownListFor(model => model.CoasterId, Model.Coaster)

Voila, the ModelState was now valid when posting.



  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: