分页类DLL - 不要重复自己

时间:2014-01-29 21:41:10

标签: c# asp.net class dll dry

我有一个简单的分页系统。我在任何地方使用它都有微小的变化我想创建一个类或DLL文件并更普遍地使用它。我不想重复自己。

我的控制者:

public ActionResult Index(int sayfa = 1)
{
    int totalPage = Posts.Count();
    int postPerPage = 10;
    int pageCount = totalPage / postPerPage;
    if ((totalPage % postPerPage) > 0)
    {
        pageCount++;
    }
    ViewBag.PageCurrent = sayfa;
    ViewBag.PageCount = pageCount;
    Posts = (IOrderedQueryable<Post>)Posts.Skip(postPerPage * (sayfa - 1)).Take(postPerPage);
    return View(Posts.ToList());
}

我的观点:

<div class="pagination">
    @{
        int pageCurrent = ViewBag.PageCurrent;
        int pageCount = ViewBag.PageCount;

        if (pageCurrent != 1)
        {
            @Html.ActionLink(" ", "Index", "Post", new { sayfa = pageCurrent - 1 }, new { @class = "previous" })
        }

        for (int i = 1; i <= pageCount; i++)
        {
            if (i == pageCurrent)
            {            
                <a href="@Url.Action("Index", "Post", new { sayfa = i, })" style="background-color: #af3425">@i</a>
            }
            else
            {
                <a href="@Url.Action("Index", "Post", new { sayfa = i } )">@i</a>
            }     
        }

        if (pageCurrent != pageCount)
        {
            @Html.ActionLink(" ", "Index", "Post", new { sayfa = pageCurrent + 1 }, new { @class = "next" })
        }
    }
    <br class="clear" />
</div>

我可以在Controller中更改的可能变量:

int postPerPage = 10; (This is not so important)

(Must-Have Changeable):

Posts = (IOrderedQueryable<Post>)Posts.Skip(postPerPage * (sayfa - 1)).Take(postPerPage);

return View(Posts.ToList());

我可以在视图中更改的可能变量:

@Url.Action("Index", "Post" .... (This is also must-have)

我希望的用法:

IN CONTROLLER:
Posts = Posts.ToMyCustomPagerClass()

IN VIEW:
@Html.Pagination()

我该怎么做? 现在我创建了下面的类,但ViewBags是有问题的。错误:名称&#39; ViewBag&#39;在当前上下文中不存在

public static class ePager<T>
{
    public static IOrderedQueryable<T> ePagedList(IOrderedQueryable<T> sinif, int page, int itemPerPage = 10)
    {
        int totalPage = sinif.Count();

        int pageCount = totalPage / itemPerPage;
        if ((totalPage % itemPerPage) > 0)
        {
            pageCount++;
        }
        ViewBag.PageCurrent = page;
        ViewBag.PageCount = pageCount;
        sinif = (IOrderedQueryable<T>)sinif.Skip(itemPerPage * (page - 1)).Take(itemPerPage);
        return sinif;
    }
}

1 个答案:

答案 0 :(得分:0)

创建一个基类,其中包含分页所需的信息,并让您的视图模型继承。在ViewBag中传递分页信息并不是很干。