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

时间:2012-11-22 11:40:51

标签: 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找不到任何插入验证摘要的位置。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

助手:

    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();
    }
});

<强>更新

如果你想使用局部视图

共享/ _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" />
}