本文介绍了ASP.NET MVC可选字段被视为必填项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字段,由于某种原因,当我单击提交"时,会收到一条确认消息,指出该字段是必需的.

I have this field that for some reason when I click on submit, gets a validation message that the field is required.

[DisplayName("Total Budget:")]
public double Budget { get; set; }

@Html.EditorFor(model => model.account.Budget)
@Html.ValidationMessageFor(model => model.account.Budget)

public class Account
{
    [DisplayName("Total Budget:")]
    public double Budget { get; set; } //dropdown
}

推荐答案

MVC中内置的DefaultModelBinder将对值类型(例如int,DateTime,十进制等)执行必需的和数据类型验证.即使您不这样做,也会发生这种情况不会使用[Required]之类的方式明确指定验证.

The built-in DefaultModelBinder in MVC will perform required and data type validation on value types like int, DateTime, decimal, etc. This will happen even if you don't explicitly specify validation using someting like [Required].

要使其成为可选,您必须将其定义为可为空:

In order to make this optional, you will have to define it as nullable:

public double? Budget { get; set; }

这篇关于ASP.NET MVC可选字段被视为必填项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 13:52