ASP.NET MVC optional field being treated as requir

2020-02-08 22:59发布

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
}

6条回答
地球回转人心会变
2楼-- · 2020-02-08 23:36

double is a value type. Value types always contain a value, even if you did not set one. That value is the default value for it's type (in this case 0.0). All value types are treated as required by the framework. The only way around this is to create a custom model binder, but that will not prevent the model from containing the default value (because there is no way to say that it wasn't entered).

So even if you create a custom binder, when you process your model, you won't be able to tell if someone entered 0 or whether that was just the default value.

Thus, the only real solution is to change your view model to use a nullable type, such as Nullable<double> (shorthand is double?).

查看更多
贼婆χ
3楼-- · 2020-02-08 23:41

You probably change Budget from a double to double?

You probably can try adding this attribute to the controller

BindExclude([Bind(Exclude="Budget")]) as well

查看更多
乱世女痞
4楼-- · 2020-02-08 23:52

You have to add the following line in the application_start (global.asax)

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Source: Unrequired property keeps getting data-val-required attribute

查看更多
迷人小祖宗
5楼-- · 2020-02-08 23:52

Use [NotMapped] annotation , this removes the required validation in the flow you also use own display attributes

查看更多
等我变得足够好
6楼-- · 2020-02-08 23:55

Use Nullable or ? after attribute name.

查看更多
在下西门庆
7楼-- · 2020-02-09 00:00

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; }
查看更多
登录 后发表回答