简体   繁体   中英

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. 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. 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. 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 id="partialSummaryDiv">@{Html.RenderPartial("YourPartial");}</div>

On the success of the Ajax call call .html() on the div not on the partial view.

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

It is not displaying in the Div because you did not define the partial view in the div. If you want the partial view hidden until the ajax success comes through, you will need to add additional logic

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.

I was able to fix the issue by using .on on the empty placeholder div.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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