【问题标题】:Required value in MVC is empty string but modelstate is still validMVC 中的必需值为空字符串,但模型状态仍然有效
【发布时间】:2014-12-13 19:59:02
【问题描述】:

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

型号

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

【问题讨论】:

  • 您是否进行了测试以查看是否有任何其他属性可能会干扰? (即只有[Required] 属性)
  • 还没有。我现在就试试
  • 我无法重现这个。显示验证消息,但未提交表单。

标签: c# asp.net-mvc


【解决方案1】:

编辑
正如@Stephen Muecke 指出的那样,我也无法重现您的案例,它应该是足够的必需属性。 正如@MajkeloDev 所说,我在下面的回答不知何故解决方法。


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

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

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

【讨论】:

  • OP有说这个字符串不能少于10个字符吗?
  • @MajkeloDev 因为HelloWorld 的长度是10。
  • @StephenMuecke 是的。请看注释
  • 不,我的意思是 OP 犯了一个愚蠢的错字或其他错误(如果没有其他问题,所声称的内容是不可能的)并且这个答案(与问题无关)有被接受
  • 其实如果Field为[Required],则表示默认不能为空,所以肯定有其他问题。这是 WorkArrond 解决方案。
猜你喜欢
  • 2021-06-23
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
相关资源
最近更新 更多