c# - MVC 中的必需值为空字符串,但模型状态仍然有效

标签 c# asp.net-mvc

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

模型

[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 指出的那样,我也无法重现您的案例,它应该足够 Required 属性。 正如@MajkeloDev 所说,我在下面的回答以某种方式解决了问题。


您应该为您的字段输入 MinimumLength = 10。数字 200 表示字符串的最大长度

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

注意:MinimumLength = 10 是一个有意义的输入的数字。对于非空字符串,MinimumLength = 1

就足够了

关于c# - MVC 中的必需值为空字符串,但模型状态仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457054/

相关文章:

c# - foreach row in datatable 为每一列添加一个asptablerow和asptablecell

c# - 如何确保数据流 block 仅按需创建线程?

c# - 没有获得 Lambda 表达式的 Intellisense

javascript - 打开或关闭 jQueryUi 对话框时触发 MVC 中的 Controller 操作

sql-server - HTML5 视频标签。某些 .MP4 视频在 Chrome 中不起作用

c# - 检查 AppDelegate 中的方法/属性是否存在

C# 转换日期

.net - MVC3 模型 DisplayFormat 和 JSON

asp.net-mvc - 我的 ViewBag 无法工作有什么原因吗?

c# - 如何在计算机锁定时按键盘键