Search code examples
validationasp.net-mvc-5html.dropdownlistformodelstateasp.net-mvc-views

MVC view exception occurs only when modelstate is not valid


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?


Solution

  • 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.