ASP.NET MVC 中的分页

发布于 2024-08-02 06:09:18 字数 426 浏览 5 评论 0原文

我有一个 asp.net 网站,我在其中使用以下代码对后面的代码进行分页:

    PagedDataSource objPds = new PagedDataSource
                                 {
                                     DataSource = ds.Tables[0].DefaultView,
                                     AllowPaging = true,
                                     PageSize = 12
                                 };

为 asp.net-mvc 进行分页的等效最佳方法是什么。我认为这实际上属于视图代码。

i have an asp.net website where i do paging through on the code behind using:

    PagedDataSource objPds = new PagedDataSource
                                 {
                                     DataSource = ds.Tables[0].DefaultView,
                                     AllowPaging = true,
                                     PageSize = 12
                                 };

what is the equivalent best way of doing paging for asp.net-mvc. I would think this would actually belong in the view code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迎风吟唱 2024-08-09 06:09:18

我只会定义一个带有页码的自定义路由:

routes.MapRoute(
                "Books", // Route name
                "books/{page}", // URL with parameters
                new {controller = "Books", action = "List", page = 1}
                );

会给你这种类型的Url:

http://localhost/books/4/

然后在你的控制器操作中你会得到这个页码:

public BooksController
{
    public ActionResult List (int page)
    {
        /* Retrieve records for the requested page from the database */

        return View ();
    }
}

所以你的视图实际上不会知道当前页面。它只会显示提供的记录列表。

您还需要直接在此视图中或在母版页中生成各个页面的链接。

I would just define a custom route with the page number in it:

routes.MapRoute(
                "Books", // Route name
                "books/{page}", // URL with parameters
                new {controller = "Books", action = "List", page = 1}
                );

Will give you this kind of Url:

http://localhost/books/4/

Then in your controller action you get this page number:

public BooksController
{
    public ActionResult List (int page)
    {
        /* Retrieve records for the requested page from the database */

        return View ();
    }
}

So your view will not actually be aware of the current page. It will just display a list of supplied records.

You will also need to generate links to various pages either in this view directly or maybe in your master page.

逆夏时光 2024-08-09 06:09:18

Nerddinner 项目中有一个很好的分页类示例:

public class PaginatedList<T> : List<T> {

        public int PageIndex  { get; private set; }
        public int PageSize   { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();
            TotalPages = (int) Math.Ceiling(TotalCount / (double)PageSize);

            this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
        }

        public bool HasPreviousPage {
            get {
                return (PageIndex > 0);
            }
        }

        public bool HasNextPage {
            get {
                return (PageIndex+1 < TotalPages);
            }
        }

There is a good paging class example in the Nerd Dinner project:

public class PaginatedList<T> : List<T> {

        public int PageIndex  { get; private set; }
        public int PageSize   { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();
            TotalPages = (int) Math.Ceiling(TotalCount / (double)PageSize);

            this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
        }

        public bool HasPreviousPage {
            get {
                return (PageIndex > 0);
            }
        }

        public bool HasNextPage {
            get {
                return (PageIndex+1 < TotalPages);
            }
        }
情未る 2024-08-09 06:09:18

如果您购买:
专业 ASP.NET MVC 1.0(Wrox 程序员到程序员)

其中关于 Ajax 和 JsonResult 的部分...非常好的演练如何设置 javascript 和非 javascript 解决方案。我还没有真正实现它,所以我不太记得它,我只记得当我读它时,我认为它非常适合我的新网站上的分页。

这里也有不错的教程:
http://www.asp.net/learn/mvc/tutorial- 32-cs.aspx

If you buy:
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)

The section in there about Ajax and JsonResult ... very good walkthrough of how to set up both an javascript and non-javascript solution. I haven't actually implemented it, so I don't remember too much about it, I just remember when I read it, I thought it would work perfectly for paging on my new site.

Decent tutorial here as well:
http://www.asp.net/learn/mvc/tutorial-32-cs.aspx

命比纸薄 2024-08-09 06:09:18

我将解释在asp.net mvc中实现分页的方法。

ProductController.cs

private ProductContext db = new ProductContext ();

public ActionResult Index()
{
    string pageString = "";
    try
    {
        pageString = Request.Url.Segments[3];
    }
    catch (Exception)
    {
        pageString = null;
    }

    int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);
    Product userModel = new Product();
    int totalProducts = userModel.GetTotalProducts();

    PaginationFunction pagination = new PaginationFunction(true);
    pagination.BaseUrl = "/Product/Index/";
    pagination.TotalRows = totalProducts;
    pagination.CurPage = page;
    pagination.PerPage = 5;
    pagination.PrevLink = "Prev";
    pagination.NextLink = "Next";
    string pageLinks = pagination.GetPageLinks();
    int start = (page - 1) * pagination.PerPage;
    int offset = pagination.PerPage;

    List<Product> products = userModel.GetProducts(start, offset);

    ViewData["title"] = "Pagination in Asp.Net Mvc";
    ViewData["totalProducts"] = totalProducts;
    ViewData["products"] = products;
    ViewData["pageLinks"] = pageLinks;

    return View(db.Products.ToList());
}

ProductModel.cs

public class Product
    {
        private ProductContext db = new ProductContext ();

        public int GetTotalProducts()
        {
            return db.Products.Count();
        }

        public List<Product> GetProducts()
        {
            return db.Products.ToList();
        }
        public List<Product> GetProducts(int start, int offset)
        {
            IEnumerable<Product> query = from m in db.Products
                                       orderby m.Id descending
                                       select m;
            query = query.Skip(start).Take(offset);
            return query.ToList();
        }

    }

Index.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <h2>View Users</h2>
    <p>
    <%: Html.ActionLink("Create New", "Create") %>
    </p>
    <p>Total Users: <strong><%= ViewData["totalProducts"] %></strong></p>

    <% if ((int)ViewData["totalProducts"] == 0)
       { %>
        <p>Sorry! No Users Found.</p>
    <% }
       else
       { %>    
    <table border="0" cellspacing="0" cellpadding="0" width="100%" class="list">
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>CreatedDate</th>
            <th>UpdatedDate</th>
            <th></th>
        </tr>

        <% foreach (Product u in (List<Product>)ViewData["products"]) 
           { %>        
            <tr>
                <td><%= u.Name%></td>
                <td><%= u.Price %></td>
                <td><%= u.CreatedDate %></td>
                <td><%= u.UpdatedDate%></td>
                <td>
                    <%: Html.ActionLink("Edit", "Edit", new { id=u.Id }) %> |
                    <%: Html.ActionLink("Details", "Details", new { id=u.Id }) %> |
                    <%: Html.ActionLink("Delete", "Delete", new { id=u.Id }) %>
                </td>
            </tr> 
        <% } %>
    </table>

        <br />
        <% if ((string)ViewData["pageLinks"] != "")
           { %>
           <%= ViewData["pageLinks"] %>
           <br /><br />
        <% } %>       
    <% } %>
</asp:Content>

I will explain the way to implement pagination in asp.net mvc.

ProductController.cs

private ProductContext db = new ProductContext ();

public ActionResult Index()
{
    string pageString = "";
    try
    {
        pageString = Request.Url.Segments[3];
    }
    catch (Exception)
    {
        pageString = null;
    }

    int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);
    Product userModel = new Product();
    int totalProducts = userModel.GetTotalProducts();

    PaginationFunction pagination = new PaginationFunction(true);
    pagination.BaseUrl = "/Product/Index/";
    pagination.TotalRows = totalProducts;
    pagination.CurPage = page;
    pagination.PerPage = 5;
    pagination.PrevLink = "Prev";
    pagination.NextLink = "Next";
    string pageLinks = pagination.GetPageLinks();
    int start = (page - 1) * pagination.PerPage;
    int offset = pagination.PerPage;

    List<Product> products = userModel.GetProducts(start, offset);

    ViewData["title"] = "Pagination in Asp.Net Mvc";
    ViewData["totalProducts"] = totalProducts;
    ViewData["products"] = products;
    ViewData["pageLinks"] = pageLinks;

    return View(db.Products.ToList());
}

ProductModel.cs

public class Product
    {
        private ProductContext db = new ProductContext ();

        public int GetTotalProducts()
        {
            return db.Products.Count();
        }

        public List<Product> GetProducts()
        {
            return db.Products.ToList();
        }
        public List<Product> GetProducts(int start, int offset)
        {
            IEnumerable<Product> query = from m in db.Products
                                       orderby m.Id descending
                                       select m;
            query = query.Skip(start).Take(offset);
            return query.ToList();
        }

    }

Index.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <h2>View Users</h2>
    <p>
    <%: Html.ActionLink("Create New", "Create") %>
    </p>
    <p>Total Users: <strong><%= ViewData["totalProducts"] %></strong></p>

    <% if ((int)ViewData["totalProducts"] == 0)
       { %>
        <p>Sorry! No Users Found.</p>
    <% }
       else
       { %>    
    <table border="0" cellspacing="0" cellpadding="0" width="100%" class="list">
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>CreatedDate</th>
            <th>UpdatedDate</th>
            <th></th>
        </tr>

        <% foreach (Product u in (List<Product>)ViewData["products"]) 
           { %>        
            <tr>
                <td><%= u.Name%></td>
                <td><%= u.Price %></td>
                <td><%= u.CreatedDate %></td>
                <td><%= u.UpdatedDate%></td>
                <td>
                    <%: Html.ActionLink("Edit", "Edit", new { id=u.Id }) %> |
                    <%: Html.ActionLink("Details", "Details", new { id=u.Id }) %> |
                    <%: Html.ActionLink("Delete", "Delete", new { id=u.Id }) %>
                </td>
            </tr> 
        <% } %>
    </table>

        <br />
        <% if ((string)ViewData["pageLinks"] != "")
           { %>
           <%= ViewData["pageLinks"] %>
           <br /><br />
        <% } %>       
    <% } %>
</asp:Content>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文