2

之前已经问过一个类似的问题(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,如果有任何错误则显示它。但是,条件的意思是当评估为假时,第一次渲染表单时,整个部分都没有渲染,所以 jquery.validate 找不到任何地方插入验证摘要。

有任何想法吗?

4

1 回答 1

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

更新:

如果您想使用局部视图

Shared/_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" />
}
于 2012-11-22T12:00:08.940 回答