Make sure that the CategoryId
property on your view model is a nullable integer:
[Required(ErrorMessage = "field required")]
public int? CategoryId { get; set; }
Also you seem to be binding your DropDownList values to a Categories
property on your view model. Ensure that this property is an IEnumerable<T>
where T
is a type containing CategoryId
and CategoryName
properties. For example:
public class CategoryViewModel
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
and now your view model could look like this:
public class MyViewModel
{
[Required(ErrorMessage = "field required")]
public int? CategoryId { get; set; }
public IList<CategoryViewModel> Categories { get; set; }
}
And most importantly inspect the generated HTML and ensure that the values of all the <option>
field of this dropdown are indeed integers:
<select class="input-validation-error" data-val="true" data-val-number="The field CategoryId must be a number." data-val-required="The CategoryId field is required." id="idCategory" name="CategoryId" style="float:left;">
<option value="">-- Select Category--</option>
<option value="1">category 1</option>
<option value="2">category 2</option>
<option value="3">category 3</option>
<option value="4">category 4</option>
<option value="5">category 5</option>
</select>
Notice the data-val-number="The field CategoryId must be a number."
attribute that gets added to the <select>
element. If the options values are not integers you will get this error.