MVC3 removed “required” but keeps getting data-val

2019-04-09 08:43发布

问题:

My Model

    [DataType(DataType.Text)]
    [Display(Name = "Number of Employee")]
    public int NumberOfEmployee { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "CEO Birthday")]
    [DateRange(2)]
    public DateTime CEO_Birthday { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Organisation Anniversary")]
    [DateRange(3)]
    public DateTime OrgAnniversary { get; set; }

My View

          <tr>
            <td style="border:0;">
                <div class="editor-label">
                    @Html.LabelFor(m => m.NumberOfEmployee)                            
                </div> 
            </td>
            <td style="border:0;">
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.NumberOfEmployee)
                </div>
            </td>
        </tr>

        <tr>
            <td style="border:0;vertical-align:middle;">
                <div class="editor-label">
                    @Html.LabelFor(m => m.CEO_Birthday)                            
                </div> 
            </td>
            <td style="border:0;">
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.CEO_Birthday, new { @class="date"})
                </div>
            </td>
        </tr>

        <tr>
            <td style="border:0;vertical-align:middle;">
                <div class="editor-label">
                    @Html.LabelFor(m => m.OrgAnniversary)                            
                </div> 
            </td>
            <td style="border:0;">
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.OrgAnniversary, new { @class = "date" })
                </div>
            </td>
          </tr>

My Global.asax.cs

protected void Application_Start()
    {
        DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
       .....
    }

There is no required property in my model but still I am getting this

I refer This to remove required field but it doesn't applicable for my code. Help me to remove required field.

回答1:

I got my answer by setting nullable Model's property ie.

    [DataType(DataType.Text)]
    [Display(Name = "Number of Employee")]
    public int? NumberOfEmployee { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "CEO Birthday")]
    [DateRange(2)]
    public DateTime? CEO_Birthday { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Organisation Anniversary")]
    [DateRange(3)]
    public DateTime? OrgAnniversary { get; set; }

NO need to add this

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;