我有一个在我家中使用分页的对象列表> index.cshtml。当用户点击每个对象页面时,我只想刷新页面的那一部分,而不是其他任何内容。我该如何做到这一点?
理想情况下,我想使用Async Methods和ControllerActions ......
控制器> HomeController.cs
public ViewResult Index(int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(viewModel);
}
主页> Index.cshtml:
@model SportsStore.WebUI.Models.ProductsListViewModel
@{
ViewBag.Title = "Products";
}
@foreach (var p in Model.Products) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
<div class="pager">
@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>
HtmlHelper&gt; PagingHelper.cs
namespace SportsStore.WebUI.HtmlHelpers {
public static class PagingHelpers {
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageUrl) {
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++) {
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
}
答案 0 :(得分:3)
你可以使用AJAX。第一步是将要刷新的内容放入部分内容并放入其自己的div中:
@model SportsStore.WebUI.Models.ProductsListViewModel
@{
ViewBag.Title = "Products";
}
<div id="products">
@Html.Partial("_products", Model.Products)
</div>
<div class="pager">
@Html.PageLinks(Model.PagingInfo, x => Url.Action("Index", new { page = x }))
</div>
然后你会得到相应的_Products.cshtml
部分:
@model IEnumerable<SportsStore.WebUI.Models.ProductViewModel>
@foreach (var p in Model.Products) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
然后调整您的控制器操作,以便它能够响应AJAX请求:
public ActionResult Index(int page = 1)
{
var viewModel = new ProductsListViewModel
{
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
if (Request.IsAjaxRequest())
{
return PartialView("_Products", viewModel);
}
return View(viewModel);
}
现在剩下的就是AJAX化你的分页锚。可以在一个单独的javascript文件中完成,您可以使用jQuery订阅它们的.click()
事件,并用AJAX请求替换默认操作:
$(function() {
$('.pager a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(products) {
$('#products').html(products);
}
});
// prevent the default redirect
return false;
});
});