andrewb
andrewb

Reputation: 3095

MVC disabling client side validation on a model field

I have a model for creating/editing items and the items can belong to a category.

The category renders as a drop down so the user can choose a category, or fill in a new category via a textbox.

The issue I am having is the dropdown seems to want to force the user to select a value from the drop down. The expected use is for that field to be optional.

Here are the relevant model properties:

[Display(Name = "Category")]
public int CategoryId { get; set; }
public System.Web.Mvc.SelectList Categories { get; set; }

And in my view:

<div class="form-group">
    @Html.LabelFor(m => m.CategoryId, new { @class = "control-label" })
    @Html.DropDownList("CategoryId", Model.Categories, "Select a category", new { @class = "form-control" })
</div>
<input type="submit" value="Create" class="btn btn-primary" title="Create new item" />

And how I set the properties in controller:

// categories is a List of POCO class with CategoryId and CategoryName fields.
Categories = new SelectList(categories, "CategoryId", "CategoryName")

When I browse to the page and click Create, the category drop down is focused on, meaning the JS deems it missing, but no error message is displayed as I do not have the ValidationMessageFor() helper set.

The rendered classes for the are

form-control input-validation-error

So how do I make this field optional?

Edit: The data-* attributes after rendering on the select are

data-val-number="The field Category must be a number." data-val-required="The Category field is required."

Upvotes: 0

Views: 33

Answers (1)

Blank Blank
Blank Blank

Reputation: 61

You have to make CategoryId nullable as :

[Display(Name = "Category")]
public int? CategoryId { get; set; }
public System.Web.Mvc.SelectList Categories { get; set; }

This way you can make Categories as an optional field.

Upvotes: 1

Related Questions