0

I've got a simple example here. Basically a form which when submitted will reload itself via an ajax request. The problem is when this happens, the unobtrusive javascript no longer works. I assume I could add the validate and unobtrusive files in the html i get back from the ajax call, but there must be an easier way to re-wire the validators, no?

Notice I'm hijacking my submit button in order to do an AJAX request which will replace the form in the dom, from the html which is returned from the ajax request.

Model:

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

Controller:

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

}

Index.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");}

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もちろん、id属性を追加する必要があります@using (Html.BeginForm("Form", "Foo"))

于 2012-08-30T16:56:37.790 に答える