Reputation: 1104
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.
Upvotes: 0
Views: 362
Reputation: 1038940
You should use a nullable type for the TypeID
property on your view model if you want to handle the non-selected case in your drop down list ("-- Select Event Type --"
):
public int? TypeID { get; set; }
You are getting the exception because if the user doesn't select any option in the dropdown, the default one is used:
<option value="">"-- Select Event Type --"</option>
Notice how the value is empty string. This obviously cannot be bound to a non-nullable integer type on your model.
Upvotes: 2