My view model has a [Required] non-nullable int property, selected by a DropDownListFor. If the list to choose from is empty, ModelState.IsValid is true.
My model has a Required int property:
public class MyModel
{
[Required]
public int PickedValue { get; set;}
IEnumerable<SelectListItem> Items { get; set; }
}
In my Create view, I render a <select> element:
@Html.DropDownListFor(model => model.PickedValue, model.Items)
And in my controller, if the model.Items list is empty (no elements to choose from), ModelState.IsValid is true:
[HttpPost]
public ActionResult Create( MyModel model )
{
if( ModelState.IsValid )
{
// true, and ModelState.Keys doesn't contain PickedValue because it was never POSTed.
}
//...
}
Now, the problem goes away if:
PickedValueisNullable(int?), or- if I have an empty item in my
<select>-@Html.DropDownListFor(model => model.PickedValue, model.Items, ""), or - if client-side validation is enabled (since the action is never fired).
Is there a way to force ModelState.IsValid to be false if some of MyModel's properties are [Required] but are missing from the POST data? Shouldn't this be the default behavior?