I have some issues with rendering a partial view using jquery. Even if it was asked more than once ( here ), I didn't found a solution that worked for me: My view:
@model IEnumerable<OdeToFood.Models.RestaurantListViewModel>
@{
ViewBag.Title = "Home Page";
}
<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>
@Html.Partial("_Restaurants", Model)
My partial view:
@model IEnumerable<OdeToFood.Models.RestaurantListViewModel>
<div id="restaurantList">
@foreach (var item in Model)
{
<div>
<h4>@item.Name</h4>
<div>@item.City, @item.Country</div>
<div>REviews: @item.CountOfReviews</div>
<hr />
</div>
}
</div>
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 action of my controller:
public ActionResult Index(string searchTerm = null)
{
var model =
_db.Restaurants
.OrderByDescending(r => r.RestaurantReviews.Average(a => a.Rating))
.Where(r => searchTerm == null || r.Name.StartsWith(searchTerm))
.Select(r => new RestaurantListViewModel
{
Id = r.Id,
Name = r.Name,
City = r.City,
Country = r.Country,
CountOfReviews = r.RestaurantReviews.Count()
}
)
.Take(10);
if (Request.IsAjaxRequest())
{
return PartialView("_Restaurants", model);
}
return View(model);
}
My issue is that nothing happens when I press search button. I've added an test alert like:
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-otf-target"));
alert('test');
$target.replaceWith(data);
});
and the alert showed when I've clicked the search button, but in site nothing happens. Anyone knows what is my issue?
You have #restaurantlist
as the target, whereas div id is actually restaurantList
. Capital "L".
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.