简体   繁体   English

jQuery AJAX Post Success将不会更新div,显示部分视图

[英]jQuery AJAX Post Success will not update div, displays partial view

I can't seem to get a jQuery AJAX post to update a div with the returned partial view. 我似乎无法获得jQuery AJAX帖子以使用返回的局部视图更新div。 The partial view is returned with the correct html and displays in its entirety within the browser but I cannot get it to display in the div I would like it to. 返回的局部视图带有正确的html,并在浏览器中完整显示,但我无法在我希望的div中显示它。 I'm sure it is something rather simple but I can't seem to figure it out after numerous hours of trying to solve this. 我敢肯定这是相当简单的事情,但是经过数小时的尝试来解决这个问题后,我似乎无法弄清楚。

Ultimately what I am trying to achieve is when the form is posted that the results are display in another div and I would then, somehow, update another div with another partial view via another ajax call. 最终,我要实现的目标是在表单发布后将结果显示在另一个div中,然后以某种方式通过另一个ajax调用以另一个局部视图更新另一个div。 I have set this test up to get familiar with how things work but I am struggling to get this right. 我已设置此测试以熟悉事物的工作原理,但我正在努力做到这一点。

Controller: 控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="id,Name")] Test test)
    {
        if (ModelState.IsValid)
        {
            db.Test.Add(test);
            db.SaveChanges();
            return PartialView("DetailsPartial", test);
        }

        return PartialView("CreatePartial");
    }

Main page: 主页:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    <button id="Create">Create</button>
</p>
<div id="CreatePlaceholder">

</div>

<div id="DetailsPlaceholder">

</div>

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

<script>
    $(document).ready(function () {
        $('#Create').click(function (event) {
            event.preventDefault();
            $.ajax({
                type: 'get',
                url: '/Test/Create'
            }).done(function (data) {
                $('#CreatePlaceholder').html(data)
            })
        })

        $('#CreateForm').submit(function (event) {
            event.preventDefault();

            var $form = $(this);
            var formData = $form.serialize;
            alert(formData);
            formData.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();

            $.ajax({
                type: 'POST',
                url: '/Test/Create',
                data: formData,
                success: function (result) {
                    $('#DetailsPlaceholder').html(result);
                }
            })
        });
    })
</script>

Create partial view: 创建局部视图:

@model PerformanceTools.Models.Test

<form id="CreateForm" method="post" action="@Url.Action("Create","Test")">
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Test</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

Details partial view: 详细局部视图:

@model PerformanceTools.Models.Test

<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.id)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.id)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Name)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Name)
    </dd>
</dl>

However you are rendering your partial view put it inside a div. 但是,您正在渲染部分视图,并将其放在div中。

 <div id="partialSummaryDiv">@{Html.RenderPartial("YourPartial");}</div>

On the success of the Ajax call call .html() on the div not on the partial view. 成功执行Ajax调用后,请在div而不是局部视图上调用.html()。

  success: function (data) {
                $('#partialSummaryDiv).html(data);
          }

It is not displaying in the Div because you did not define the partial view in the div. 它没有显示在Div中,因为您没有在div中定义局部视图。 If you want the partial view hidden until the ajax success comes through, you will need to add additional logic 如果您希望在ajax成功通过之前隐藏部分视图,则需要添加其他逻辑

The problem was that the event was never being hooked up to the forms submit due to it being added to the page after the DOM was ready. 问题在于该事件从未挂接到表单提交,因为在DOM准备就绪后将其添加到页面中。

I was able to fix the issue by using .on on the empty placeholder div. 我可以通过在空的占位符div上使用.on来解决此问题。

    $('#CreatePlaceholder').on('submit', '#CreateForm', function (event) {
        event.preventDefault();

        var formData = $(this).serialize();
        formData.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();

        $.ajax({
            type: 'POST',
            url: '/Test/Create',
            data: formData
        }).done(function (data) {
            $('#DetailsPlaceholder').html(data);
        })
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM