0

我这里有一个简单的例子。基本上是一个表单,提交时将通过 ajax 请求重新加载自己。问题是当这种情况发生时,不显眼的 javascript 不再起作用。我假设我可以在我从 ajax 调用返回的 html 中添加验证和不显眼的文件,但是必须有一种更简单的方法来重新连接验证器,不是吗?

请注意,我正在劫持我的提交按钮,以便执行 AJAX 请求,该请求将替换 dom 中的表单,来自 ajax 请求返回的 html。

模型:

    public class Foo
    {
        public int Bar { get; set; }
    }

控制器:

public class FooController : Controller
{

    public ActionResult Index()
    {
        return View(new Foo{});
    }

    [HttpPost]
    public ActionResult Form(Foo model)
    {
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(Foo model)
    {
        return View();
    }

}

索引.cshtml

@model PartialPostBackValidation.Models.Foo

@{
    ViewBag.Title = "Index";
}

<h2>@Html.ActionLink("Index", "Index")</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<script>
    $(function () {
        $("body").on("click", ".ajax-submit", function () {
            var form = $(this).parents("form");
            $.post(
                form.attr("action"),
                form.serialize(),
                function (html) {
                    form.replaceWith(html);
                }
            );
            return false;
        });
    });
</script>


@{Html.RenderPartial("Form");}

表单.cshtml

@model PartialPostBackValidation.Models.Foo

@{
    ViewBag.Title = "Index";
    Layout = null;
}

@using (Html.BeginForm("Form", "Foo")) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Foo</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Bar)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Bar)
            @Html.ValidationMessageFor(model => model.Bar)
        </div>
        <p>
            <input type="submit" value="Create" class="ajax-submit" />
        </p>
    </fieldset>
}
4

1 回答 1

2

要使验证正常工作,您只需在动态加载内容后在表单上重新启用它:

$('#form-id').removeData('validator');
$('#form-id').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('#form-id');   <<<<<< Just having this could be enough but some people complain that without removingData first it doesn’t always work.

ps 当然你需要在你的@using (Html.BeginForm("Form", "Foo"))

于 2012-08-30T16:56:37.790 回答