MVC3删除了“required”但仍然获得了data-val-required属性

时间:2013-01-22 05:49:58

标签: asp.net asp.net-mvc-3

我的模型

    [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; }

我的查看

          <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>

我的 Global.asax.cs

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

我的模型中没有必需的属性,但我仍然得到了这个

enter image description here

我引用This删除必填字段但不适用于我的代码。帮我删除必填字段。

1 个答案:

答案 0 :(得分:16)

我通过设置可以为空的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; }

无需添加此

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;