简体   繁体   中英

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."

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM