c# – MVC中的必需值为空字符串,但modelstate仍然有效

我的模型有一个必需的字符串,我可以提交表单,仍然将文本框留空,模型状态返回为有效,所以我不知道我做错了什么.这是我的页面上唯一一个这样做的控件.这是我的代码:

模型

[Required(ErrorMessage = "Requirements are Required.")]
[DataType(DataType.MultilineText, ErrorMessage = "Requirements is Required.")]
[StringLength(200, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]
public string Requirements { get; set; }

视图

<div class="form-group">
    @Html.LabelFor(model => model.Requirements, "Requirements:", htmlAttributes: new { @class = "col-sm-4 control-label" })
    <div class="col-sm-8">
        @Html.TextAreaFor(model => model.Requirements, htmlAttributes: new { @rows = "10", @cols = "50", @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Requirements)
    </div>

最佳答案 编辑:

正如@Stephen Muecke所说,我不能重现你的情况,它应该足够必需的属性.

我的回答如下@MajkeloDev所说的解决方法.

您应该为您的字段添加MinimumLength = 10.数字200表示字符串的最大长度

[StringLength(200, MinimumLength = 10, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]

注意:MinimumLength = 10是有意义输入的某个数字.对于非空字符串,MinimumLength = 1就足够了

点赞