ASP.NET MVC optional field being treated as required

前端 未结 6 2010
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 02:57

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          


        
相关标签:
6条回答
  • 2020-12-15 03:41

    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

    0 讨论(0)
  • 2020-12-15 03:45

    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

    0 讨论(0)
  • 2020-12-15 03:52

    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; }
    
    0 讨论(0)
  • 2020-12-15 03:53

    Use Nullable or ? after attribute name.

    0 讨论(0)
  • 2020-12-15 03:56

    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?).

    0 讨论(0)
  • 2020-12-15 03:57

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

    0 讨论(0)
提交回复
热议问题