I have a model class "Country" with property "CultureId" that is NOT marked as required. Another class "CountryViewModel" holds the same property "CultureId".
When rendering the "Create" view, I noticed that validation data attributes were added to the "CultureId" textbox, although there were no data annotations added.
I am using
@Html.HiddenFor(mode => mode.CultureId)
What might be the cause for such a behavior?
Thanks
The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.
Adding Validation to ModelThe validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation.
In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.
I'm guessing your CultureId is an int. MVC automatically adds required tags to non-nullable value types.
To turn this off add
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
to Application_Start or make your int nullable
There are couple of ways to handle this -
a). Make the property as Nullable like
public int? Age { get; set; }
b). Use the below in controller class -
ModelState["Age"].Errors.Clear();
c). Add to the startup- DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With