Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC optional field being treated as required

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
}
like image 978
user1662812 Avatar asked Nov 08 '12 16:11

user1662812


3 Answers

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; }
like image 65
Jerad Rose Avatar answered Nov 02 '22 10:11

Jerad Rose


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

like image 10
Nahuel García Avatar answered Nov 02 '22 09:11

Nahuel García


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

like image 8
Erik Funkenbusch Avatar answered Nov 02 '22 09:11

Erik Funkenbusch