2010-03-18 63 views
4

我在ASP.NET MVC視圖上實現分頁,我想從視圖調用控制器中的方法。ASP.NET MVC:從視圖調用控制器方法

代碼視圖:

<a href="<%= Url.Action("Search", 
      new { page = NextPage(Request["exactPage"])).ToString()}) %>"> 

控制器的方法:

public string NextPage(string currentPage) 
{ 
    return (int.Parse(currentPage) + 1).ToString(); 
} 

我如何可以調用視圖中的下一頁方法?

謝謝!

+0

@愛麗絲夢遊仙境:您可以通過將文本縮進4格(選擇並按下Ctrl + K)來將文本格式化爲代碼。這將允許你使用像'<'這樣的特殊字符而沒有問題。 – 2010-03-18 20:13:41

回答

2

如果您知道當前頁面的數量,你能不能只呈現鏈接,其中頁值= 當前頁加/減1上一頁和下一頁的鏈接?您並不需要視圖來詢問控制器下一頁/上一頁的頁碼。該信息可以通過基於當前頁面索引值的視圖派生。

編輯:我建議控制器向視圖傳遞一個附加值,指出可用頁面的總數。該視圖然後可以將該值與當前頁碼進行比較以確定是否顯示下一個鏈接。

+0

是的,但你會繼續下去,所以如果最後一頁是3,下一頁將繼續上升到100或其他任何。所以我希望它保持在它到達最後一頁的位置......這是邏輯我寧願放在一個方法... – 2010-03-18 20:23:42

+0

@Alice在仙境:看我的編輯。 – pmarflee 2010-03-18 20:28:03

2

我忘記它來自哪裏。也許有人可以在這裏發佈鏈接作爲評論。

我認爲這是代碼完整。

我有這個作爲一個項目;

MvcPaging;

IPagedList

using System.Collections.Generic; 

namespace MvcPaging 
{ 
    public interface IPagedList<T> : IList<T> 
    { 
     int PageCount { get; } 
     int TotalItemCount { get; } 
     int PageIndex { get; } 
     int PageNumber { get; } 
     int PageSize { get; } 
     bool HasPreviousPage { get; } 
     bool HasNextPage { get; } 
     bool IsFirstPage { get; } 
     bool IsLastPage { get; } 
    } 
} 

PagedList

using System; 
using System.Collections.Generic; 
using System.Linq; 
using MvcPaging; 

namespace MvcPaging 
{ 
    public class PagedList<T> : List<T>, IPagedList<T> 
    { 
     public PagedList(IEnumerable<T> source, int index, int pageSize) 
      : this(source, index, pageSize, null) 
     { 
     } 

     public PagedList(IEnumerable<T> source, int index, int pageSize, int? totalCount) 
     { 
      Initialize(source.AsQueryable(), index, pageSize, totalCount); 
     } 

     public PagedList(IQueryable<T> source, int index, int pageSize) 
      : this(source, index, pageSize, null) 
     { 
     } 

     public PagedList(IQueryable<T> source, int index, int pageSize, int? totalCount) 
     { 
      Initialize(source, index, pageSize, totalCount); 
     } 

     #region IPagedList Members 

     public int PageCount { get; private set; } 
     public int TotalItemCount { get; private set; } 
     public int PageIndex { get; private set; } 
     public int PageNumber { get { return PageIndex + 1; } } 
     public int PageSize { get; private set; } 
     public bool HasPreviousPage { get; private set; } 
     public bool HasNextPage { get; private set; } 
     public bool IsFirstPage { get; private set; } 
     public bool IsLastPage { get; private set; } 

     #endregion 

     protected void Initialize(IQueryable<T> source, int index, int pageSize, int? totalCount) 
     { 
      //### argument checking 
      if (index < 0) 
      { 
       throw new ArgumentOutOfRangeException("PageIndex cannot be below 0."); 
      } 
      if (pageSize < 1) 
      { 
       throw new ArgumentOutOfRangeException("PageSize cannot be less than 1."); 
      } 

      //### set source to blank list if source is null to prevent exceptions 
      if (source == null) 
      { 
       source = new List<T>().AsQueryable(); 
      } 

      //### set properties 
      if (!totalCount.HasValue) 
      { 
       TotalItemCount = source.Count(); 
      } 
      PageSize = pageSize; 
      PageIndex = index; 
      if (TotalItemCount > 0) 
      { 
       PageCount = (int)Math.Ceiling(TotalItemCount/(double)PageSize); 
      } 
      else 
      { 
       PageCount = 0; 
      } 
      HasPreviousPage = (PageIndex > 0); 
      HasNextPage = (PageIndex < (PageCount - 1)); 
      IsFirstPage = (PageIndex <= 0); 
      IsLastPage = (PageIndex >= (PageCount - 1)); 

      //### add items to internal list 
      if (TotalItemCount > 0) 
      { 
       AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); 
      } 
     } 
    } 
} 

尋呼機

using System; 
using System.Text; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace MvcPaging 
{ 
    public class Pager 
    { 
     private ViewContext viewContext; 
     private readonly int pageSize; 
     private readonly int currentPage; 
     private readonly int totalItemCount; 
     private readonly RouteValueDictionary linkWithoutPageValuesDictionary; 

     public Pager(ViewContext viewContext, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary) 
     { 
      this.viewContext = viewContext; 
      this.pageSize = pageSize; 
      this.currentPage = currentPage; 
      this.totalItemCount = totalItemCount; 
      this.linkWithoutPageValuesDictionary = valuesDictionary; 
     } 

     public string RenderHtml() 
     { 
      int pageCount = (int)Math.Ceiling(this.totalItemCount/(double)this.pageSize); 
      int nrOfPagesToDisplay = 10; 

      var sb = new StringBuilder(); 

      // Previous 
      if (this.currentPage > 1) 
      { 
       sb.Append(GeneratePageLink("Previous", this.currentPage - 1)); 
      } 
      else 
      { 
       sb.Append("<span class=\"disabled\">Previous</span>"); 
      } 

      int start = 1; 
      int end = pageCount; 

      if (pageCount > nrOfPagesToDisplay) 
      { 
       int middle = (int)Math.Ceiling(nrOfPagesToDisplay/2d) - 1; 
       int below = (this.currentPage - middle); 
       int above = (this.currentPage + middle); 

       if (below < 4) 
       { 
        above = nrOfPagesToDisplay; 
        below = 1; 
       } 
       else if (above > (pageCount - 4)) 
       { 
        above = pageCount; 
        below = (pageCount - nrOfPagesToDisplay); 
       } 

       start = below; 
       end = above; 
      } 

      if (start > 3) 
      { 
       sb.Append(GeneratePageLink("1", 1)); 
       sb.Append(GeneratePageLink("2", 2)); 
       sb.Append("..."); 
      } 
      for (int i = start; i <= end; i++) 
      { 
       if (i == this.currentPage) 
       { 
        sb.AppendFormat("<span class=\"current\">{0}</span>", i); 
       } 
       else 
       { 
        sb.Append(GeneratePageLink(i.ToString(), i)); 
       } 
      } 
      if (end < (pageCount - 3)) 
      { 
       sb.Append("..."); 
       sb.Append(GeneratePageLink((pageCount - 1).ToString(), pageCount - 1)); 
       sb.Append(GeneratePageLink(pageCount.ToString(), pageCount)); 
      } 

      // Next 
      if (this.currentPage < pageCount) 
      { 
       sb.Append(GeneratePageLink("Next", (this.currentPage + 1))); 
      } 
      else 
      { 
       sb.Append("<span class=\"disabled\">Next</span>"); 
      } 
      return sb.ToString(); 
     } 

     private string GeneratePageLink(string linkText, int pageNumber) 
     { 
      var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary); 
      pageLinkValueDictionary.Add("page", pageNumber); 
      //var virtualPathData = this.viewContext.RouteData.Route.GetVirtualPath(this.viewContext, pageLinkValueDictionary); 
      var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary); 

      if (virtualPathData != null) 
      { 
       string linkFormat = "<a href=\"{0}\">{1}</a>"; 
       return String.Format(linkFormat, virtualPathData.VirtualPath, linkText); 
      } 
      else 
      { 
       return null; 
      } 
     } 
    } 
} 

個PagingExtensions

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 
using System.Web.Routing; 
using MvcPaging; 

namespace MvcPaging 
{ 
    public static class PagingExtensions 
    { 
     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount) 
     { 
      return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, null); 
     } 

     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName) 
     { 
      return Pager(htmlHelper, pageSize, currentPage, totalItemCount, actionName, null); 
     } 

     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, object values) 
     { 
      return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, new RouteValueDictionary(values)); 
     } 

     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName, object values) 
     { 
      return Pager(htmlHelper, pageSize, currentPage, totalItemCount, actionName, new RouteValueDictionary(values)); 
     } 

     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary) 
     { 
      return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, valuesDictionary); 
     } 

     public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName, RouteValueDictionary valuesDictionary) 
     { 
      if (valuesDictionary == null) 
      { 
       valuesDictionary = new RouteValueDictionary(); 
      } 
      if (actionName != null) 
      { 
       if (valuesDictionary.ContainsKey("action")) 
       { 
        throw new ArgumentException("The valuesDictionary already contains an action.", "actionName"); 
       } 
       valuesDictionary.Add("action", actionName); 
      } 
      var pager = new Pager(htmlHelper.ViewContext, pageSize, currentPage, totalItemCount, valuesDictionary); 
      return pager.RenderHtml(); 
     } 

     public static IPagedList<T> ToPagedList<T>(this IQueryable<T> source, int pageIndex, int pageSize) 
     { 
      return new PagedList<T>(source, pageIndex, pageSize); 
     } 

     public static IPagedList<T> ToPagedList<T>(this IQueryable<T> source, int pageIndex, int pageSize, int totalCount) 
     { 
      return new PagedList<T>(source, pageIndex, pageSize, totalCount); 
     } 

     public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> source, int pageIndex, int pageSize) 
     { 
      return new PagedList<T>(source, pageIndex, pageSize); 
     } 

     public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> source, int pageIndex, int pageSize, int totalCount) 
     { 
      return new PagedList<T>(source, pageIndex, pageSize, totalCount); 
     } 
    } 
} 

然後在我的控制器;

public class IndexArticlesFormViewModel 
{ 
    public IPagedList<Article> articles {get; set;} 
    public IQueryable<string> userTags { get; set; } 
    public string tag {get; set;} 
} 


    public ActionResult SearchResults(int? page, string tag) 
    { 
     IndexArticlesFormViewModel fvm = new IndexArticlesFormViewModel(); 
     fvm.articles = ar.Search(tag).ToPagedList(page.HasValue ? page.Value - 1 : 0, 8); 
     fvm.tag = tag; 

     return View(fvm); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult SearchResults(int? page, string tag, FormCollection collection) 
    { 
     if (!string.IsNullOrEmpty(collection["txtSearch"])) 
      return RedirectToAction("SearchResults", new {page = 1, tag = collection["txtSearch"] }); 

     return RedirectToAction("SearchResults", new { page = page, searchTerm = tag }); 
    } 

然後查看;

<div class="pager"> 
    <%= Html.Pager(ViewData.Model.articles.PageSize, ViewData.Model.articles.PageNumber, ViewData.Model.articles.TotalItemCount, new { tag = Model.tag })%> 
</div> 
+0

http://pagedlist.codeplex.com/ – jasonmw 2010-03-19 04:07:46

+0

謝謝@Jason。我實際上已經發現了幾個對這段代碼的引用,並且可能最後不記得它來自哪裏。雖然工作很好 – griegs 2010-03-19 04:17:00

0

正如其他人所建議的,一個的HtmlHelper可能是適當的在這裏,但如果你想調用靜態方法上的一些其他類,你可以再補充一個命名空間導入到您的視圖的頂部。

<%@ Import Namespace="YOURCONTROLLERNAMESPACE"%> 
相關問題