I got an exception when user submitted a form without selecting any value in the dropdownlistfor as follows:
<div class="editor-field">
@Html.DropDownListFor(
x => x.TypeID,
new SelectList(ViewBag.EventType, "ID", "Name"),
"-- Select Event Type --"
)
@Html.ValidationMessageFor(model => model.TypeID)
</div>
I got an exception:
Value cannot be null. Parameter name: items
I think I have to check if user selected a value or make an alert, but I’m not sure how to make it.
You should use a nullable type for the
TypeIDproperty on your view model if you want to handle the non-selected case in your drop down list ("-- Select Event Type --"):You are getting the exception because if the user doesn’t select any option in the dropdown, the default one is used:
Notice how the value is empty string. This obviously cannot be bound to a non-nullable integer type on your model.