ASP.NET MVC Adds Confirmation for Optional Fields

I have a Country model class with the CultureId property that is NOT marked as required. Another class "CountryViewModel" has the same property "CultureId".

When visualizing the Create view, I noticed that validation data attributes were added to the CultureId text box, although data annotations were added.

I use

@Html.HiddenFor(mode => mode.CultureId) 

What could be causing this behavior?

thanks

+6
source share
4 answers

I assume your CultureId is an int. MVC automatically adds the required tags to value types that are not null values.

To disable this, add

 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 

in Application_Start or make your int nullable

+12
source

There are several ways to handle this -
a). Make the property Nullable as

 public int? Age { get; set; } 

b) Use below in controller class -

 ModelState["Age"].Errors.Clear(); 

from). Add to top - DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

+8
source

if you can use data annotations you should check this http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx

 namespace MvcApplication1.Models { [MetadataType(typeof(MovieMetaData))] public partial class Movie { } public class MovieMetaData { [Required] public object Title { get; set; } [Required] [StringLength(5)] public object Director { get; set; } [DisplayName("Date Released")] [Required] public object DateReleased { get; set; } } 

}

it helps you set modelless checks on the database side.

0
source

try the following:

 ModelState["CultureId"].Errors.Clear(); if (ModelState.IsValid) { ..... } 

If CultureId is int then it will also give you the desired result ...

0
source

Source: https://habr.com/ru/post/912027/


All Articles