Joseph
Joseph

Reputation: 849

Getting different validation message "must be a number" for dropdownListFor

I have a DropDownListFor for which i have validation message as "field required"

@Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.Categories, "CategoryId", "CategoryName"), "-- Select Category--", new { id = "idCategory", style = "float:left;" })
@Html.ValidationMessageFor(model => model.CategoryId) 

but i'm always getting errormessage as "The field CategoryId must be a number"

my model

[Required(ErrorMessage = "This field is required")]
public long CategoryId { get; set; }

Upvotes: 1

Views: 2910

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

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.

Upvotes: 4

Related Questions