ValidationMessage是显示在页面加载
问题描述:
我有一块剃刀代码如下所示:ValidationMessage是显示在页面加载
<div class="form-group">
@Html.Label("State", new { @class = "control-label col-md-4" })
<div class="col-md-8">
<div class="tt-container">
@Html.Editor("StateName", new { htmlAttributes = new { @id = "StateName", @class = "form-control", @required="required" } })
</div>
@Html.ValidationMessage("StateName", "The State field is required", new { @class = "text-danger" })
</div>
</div>
验证消息The State field is required
是显示在页面加载。我只希望在用户尝试提交表单时该消息显示该文本框是否为空。
如果我这样做:
@Html.ValidationMessage("StateName", "", new { @class = "text-danger" })
那么很明显,我看不出有任何的验证信息,因为它是空的,但是当我点击提交,并且文本框为空,我得到一个验证消息说This field is required
。
我在寻找2种可能性中的1种。
第一个问题,如果相应的文本框是空的,我可以在提交按钮之后显示验证消息吗?
第二个问题,我可以得到这个错误信息是更像The State field is required
描述性?
任何帮助表示赞赏。
答
你可以使用这个ValidationMessage
辅助方法过载
@Html.ValidationMessage("StateName")
验证消息将是通过在形式模型验证框架生成的消息“{propertyName的}需要”
我知道,这但它需要在模型中使用强类型属性。我所拥有的仅仅是一个简单的文本框,当输入内容时,该值绑定到一个隐藏的元素 –
'StateName'不是一个强类型属性。只是一个供用户查看的文本框,但该值绑定到强类型的hiddenfor元素 –
您也可以使用'ValidationMessage'辅助方法的相同内容。使用带有主要名称的过载。查看更新后的答案。 – Shyju