Search in Help for developer site.

Tuesday 5 July 2016

How to Disable Required Attribute for Value Types in MVC

In ASP.NET MVC value type data types will be set to required field and these fields are required on click of submit button.
lets take an example of Student modal class

    public class Student
    {
        public int StudentID { get; set; }
        public string Name { get; set; }
        public DateTime DOB { get; set; }
    }

So StudentID and DOB field will be marked as required field on click of submit button in any form.

In some circumstances we don't need this and we want to disable it and to do so there are 2 solution.
  1. You just need to add this code in your global.asax file.(Recommended)

DataAnnotationsModelValidatorProvider
    .AddImplicitRequiredAttributeForValueTypes = false;
It will disable adding implicitly required attribute to value types.
 
      2. Make it null

     public class Student
    {
        public int? StudentID { get; set; }
        public string Name { get; set; }
        public DateTime? DOB { get; set; }
    }



 

7 comments: