jquery - 自定义 ValidationSummary 模板(不会破坏客户端验证)

标签 jquery asp.net-mvc asp.net-mvc-3 jquery-validate client-side-validation

之前曾问过类似的问题( 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/

相关文章:

c# - 与模型状态错误消息相对的成功消息

c# - ASP.Net MVC3 Razor 网站 session 变量在 CHROME 中消失

javascript - 获取所有选定的值()'s from a multiselect container per it'自己点击:event?

javascript - JQuery 响应式菜单不起作用

php - 调用JS函数时销毁 session 变量

javascript - 使 jQuery 字符循环插件不引人注目的最佳解决方案是什么?

c# - 如何让 RazorEngine Parse 方法成功处理布局?

javascript - 重定向页面上的超时请求无法路由到另一个 Angular View

asp.net-mvc - 换行问题 - C# .NET MVC

javascript - MVC3 Razor 无法识别何时停止解析