ASP.NET MVC optional field being treated as requir

2020-02-08 23:48发布

问题:

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
}

回答1:

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; }


回答2:

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:

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



回答4:

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



回答5:

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



回答6:

Use Nullable or ? after attribute name.