Partial view not rendering with asynch request for update

扶醉桌前 提交于 2019-12-13 04:24:14

问题



My objective


is to make an asynchronous call in my jquery file(otf.js) that updates my restaurant list in my home page (index.cshtml) with a Search term entered in the form that filters the restaurant results. otf.js is in a bundle, and is rendered in the layout view.


My Problem


is that I enter a search term and submit my form, and the list updates as expected, but when entering a new search term and clicking submit, the list does not change. It needs to change every time I enter a new search result and click submit.


My source code

otf.js


$(function () {

    var ajaxFormSubmit = function () {
        var $form = $(this);

        var options = {
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: $form.serialize()
        };

        $.ajax(options).done(function (data) {
            var $target = $($form.attr("data-otf-target"));
            $target.replaceWith(data);
        });

        return false;
    };

    $("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});

index.cshtml


@model IEnumerable<OdeToFood.Models.RestaurantListViewModel>

@{
    ViewBag.Title = "Home Page";
}
<hr />

<form method="get" action="@Url.Action("index")"
        data-otf-ajax="true" data-otf-target="#restaurantList">
    <input type="search" name="searchTerm" />
    <input type="submit" value="Search By Name" />
</form>

<div id="restaurantList">
    @Html.Partial("_Restaurants", Model)
</div>

_Restaurants.cshtml (a partial view)


@model IEnumerable<OdeToFood.Models.RestaurantListViewModel>

   @foreach (var item in Model)
    {
        <div>
            <h4>@item.Name</h4>
            <div>
                @item.City, @item.Country

            </div>
            <div>
                Reviews: @item.CountOfReviews

            </div>
            <hr />

        </div>
    }

回答1:


The problem is that <div id="restaurantList"> is wrapping around the @Html.Partial("_Restaurants", Model) line in index.cshtml, and it needs to be wrapped around the @foreach code block in the partial view _Restaurants.cshtml

I made this change to my code, and presto, the restaurant list was updated every time i clicked the search button, not just the first time.

Now the only question is why does this cause the list not to update after the first time?




回答2:


Looks like you are removing form from DOM to be replaced by new form. In this case, you should delegate event.

So:

$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);

Become: { here i use document as delegate, but better is to use closest static container of the form }

$(document).on('submit',"form[data-otf-ajax='true']",ajaxFormSubmit);


来源:https://stackoverflow.com/questions/16901233/partial-view-not-rendering-with-asynch-request-for-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!