问题
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