之前曾问过类似的问题( Custom ValidationSummary template Asp.net MVC 3 ),但两个答案都不满足我的额外要求,即该解决方案不会破坏客户端验证。
那么,有谁知道如何获得这样的功能:
@if (!ViewData.ModelState.IsValid)
{
<div class="form-errors">
<p>Please have another look at the fields highlighted below</p>
@Html.ValidationSummary()
</div>
}
可以与客户端验证一起使用吗?
当客户端验证关闭时,这正是我想要的,即,如果模型有效,则排除整个 div,如果有任何错误,则显示它。但是,条件意味着当评估为 false 时首次渲染表单时,不会渲染整个部分,因此 jquery.validate 无法找到任何位置来插入验证摘要。
有什么想法吗?
最佳答案
帮助者:
public static MvcHtmlString MyValidationSummary(this HtmlHelper helper, bool excludePropertyErrors = false)
{
string html = "";
html += helper.ViewData.ModelState.IsValid ? "<div class='form-errors' style='display:none;'>" : "<div class='form-errors'>";
html += "<p>Please have another look at the fields highlighted below</p>";
html += helper.ValidationSummary(excludePropertyErrors);
html += "</div>";
return new MvcHtmlString(html);
}
查看:
@using (Html.BeginForm("Index", "Home",FormMethod.Post, new {id="myform"}))
{
@Html.MyValidationSummary()
...
<input type="button" id="submitbutton" value="Submit" />
}
JS:
$("#submitbutton").click(function () {
$("#myform").validate();
if (!$("#myform").valid()) {
$("#myform .form-errors").show();
}
else {
$("#myform").submit();
}
});
更新:
如果你想使用部分 View
共享/_MyValidationSummary.cshtml
@if (!ViewData.ModelState.IsValid)
{
<div class="form-errors">
<p>Please have another look at the fields highlighted below</p>
@Html.ValidationSummary()
</div>
}
else
{
<div class="form-errors" style="display:none;">
<p>Please have another look at the fields highlighted below</p>
@Html.ValidationSummary()
</div>
}
查看:
@using (Html.BeginForm("Index", "Home",FormMethod.Post, new {id="myform"}))
{
@Html.Partial("_MyValidationSummary")
...
<input type="button" id="submitbutton" value="Submit" />
}
关于jquery - 自定义 ValidationSummary 模板(不会破坏客户端验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13512023/