【问题标题】:Unobtrusive Javascript - And Ajax Requests不显眼的 Javascript - 和 Ajax 请求
【发布时间】:2012-08-25 09:35:35
【问题描述】:

我这里有一个简单的例子。基本上是一个表单,提交时将通过 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();
    }

}

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>
}

【问题讨论】:

    标签: asp.net-mvc validation razor unobtrusive-javascript


    【解决方案1】:

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

    $('#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.
    

    附言当然,您需要在 @using (Html.BeginForm("Form", "Foo")) 中添加一个 id 属性

    【讨论】:

    • 这很棒——它确实进行了验证——有没有办法使用 javascript 来查看我的验证器是否失败?
    • 使用 JQuery 验证? if ($('#id').valid()) {"hello world";}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2011-03-31
    • 2011-06-10
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多