0

I am coding a MVC 5 internet application and an error is being reported when my model does not validate.

This is error is in my create view as follows:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'assetCategory' is of type 'System.String' but must be of type 'IEnumerable'.

At this line of code:

@Html.DropDownListFor(m => m.assetCategory, Model.assetCategories, htmlAttributes: new { @class = "form-control" })

Here are the relevant fields:

public IEnumerable<SelectListItem> assetCategories { get; set; }
public string assetCategory { get; set; }

Here is the full group code:

<div class="form-group">
    @Html.LabelFor(model => model.assetCategory, null, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.assetCategory, Model.assetCategories, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.assetCategory, "", new { @class = "text-danger" })
    </div>
</div>

This error only happens if the model does not validate. If the model does validate, then no error occurs, and the dropdownlist is populated and I can retrieve the selected value in the assetCategory string.

May I please have some help with this code?

Simon
  • 7,991
  • 21
  • 83
  • 163
  • You have not shown your controller code but when your return the view if invalid, have you reassigned the `SelectList` for model.assetCategories? –  Oct 13 '14 at 08:35
  • Thank you Stephen, that is all I needed to do. – Simon Oct 13 '14 at 08:46

1 Answers1

0

Make sure your not passing the Model.assetCategories as null, you must ensure that the data is loaded for that property else this error will throw.

Venkatesh
  • 1,204
  • 1
  • 10
  • 18