Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC adds Validation for non-required fields

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

like image 616
Bill Avatar asked Mar 30 '12 08:03

Bill


People also ask

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.

How we can implement validation in MVC?

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.

Can we do validation in MVC using data annotations?

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.


2 Answers

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

like image 126
Dan Avatar answered Oct 14 '22 09:10

Dan


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;

like image 37
Divyans Mahansaria Avatar answered Oct 14 '22 09:10

Divyans Mahansaria