简体   繁体   English

MVC 在 model 字段上禁用客户端验证

[英]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.我有一个 model 用于创建/编辑项目,这些项目可以属于一个类别。

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.我遇到的问题是下拉菜单似乎想强制用户从下拉菜单中选择 select 一个值。 The expected use is for that field to be optional.该字段的预期用途是可选的。

Here are the relevant model properties:以下是相关的 model 属性:

[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:以及我如何在 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.当我浏览到该页面并单击“创建”时,将关注类别下拉列表,这意味着 JS 认为它丢失了,但没有显示错误消息,因为我没有设置 ValidationMessageFor() 帮助器。

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编辑:在 select 上渲染后的 data-* 属性是

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:您必须将CategoryId设为可为空:

[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.这样,您可以将类别设置为可选字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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