@Html.TextAreaFor() 始终按要求进行验证,即使注释为可为空

@Html.TextAreaFor() always validated as required even if annotated as nullable

为什么 TextAreaFor 总是按照 mvc 中的要求进行验证,即使使用以下注释也是如此:

public class DepartmentViewModel
{
    public int Id { get; set; }

    [Required]
    [Display(Name ="Department Name")]
    public string DepartmentName { get; set; }


    [Display(Name = "Remarks")]
    [DataType(DataType.MultilineText)]
    [Required(AllowEmptyStrings = true), 
     DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Remarks { get; set; }

    [Display(Name = "Cost Center")]
    public int ? CostCenterId { get; set; }
}

在视图部分我使用了这个:

<div class="form-group">
                    @Html.LabelFor(m => m.Remarks, new { @class = "control-label col-md-2 col-sm-12" })
                    <div class="col-sm-12 col-md-8">
                        @Html.ValidationMessageFor(m => m.Remarks, "", new { @class = "text-danger" })
                        @Html.TextAreaFor(m => m.Remarks, new { @class = "form-control", style = "resize: none;", @rows = 10 })
                    </div>
</div>

如果我将其更改为 TextBoxFor,一切正常。我想将备注标记为可选,但使用 TextAreaFor 它始终是必需的。

删除 [Required][DisplayFormat] 属性。您还可以删除 [DataType] 属性,因为它仅在使用 @Html.EditorFor() 时适用。您的 属性 只需

[Display(Name = "Remarks")]
public string Remarks { get; set; }

尽管 [Display] 属性也不是必需的,因为它与 属性 名称相同。