使用Ajax和MvcContrib Grid添加分页和排序功能

时间:2011-08-07 17:27:22

标签: ajax sorting paging mvccontrib

我在我的MVC应用程序中使用MvcContrib Grid控件。按照Pro * ASP.NET MVC一书中的示例,我创建了以下类和分页助手

公共类PagingInfo

{
    public int TotalItems { get; set; }
    public int ItemsPerPage { get; set; }
    public int CurrentPage { get; set; }
    public int TotalPages
    {
        get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
    }

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.AppendLine(tag.ToString());
        }
        return MvcHtmlString.Create(result.ToString());
    }
}

在我的视图中,我有以下内容:

    页面:@ Html.PageLinks(ViewBag.Paging为PagingInfo,i =&gt; Url.Action(“Index”,new {pageNo = i}))
 @Html.DropDownList("pageSize", new SelectList(new[] { "2", "25", "50", "75", "100", "200" }), "-Select-", new { @style = "width:75px" })   

1) 如何使用Url.Action将pageSize(行数)发送到帮助程序类?

2) 我还定义了以下函数来启用ajax。这是一种有效的方法吗?我也将使用类似的功能进行治疗。所以你的意见将不胜感激。

$(“#pageLinks a”)。live(“click”,function(){

    $.get($(this).attr("href"), function(response) {
        $("#Grid").replaceWith(response); 
    });

    return false;


});

谢谢,

1 个答案:

答案 0 :(得分:0)

如果其他人遇到同样的问题,请发送其他参数。我更改了我的html帮助函数,如下所示: -

public static MvcHtmlString PageLinks(this HtmlHelper html,
                                              PagingInfo pagingInfo,
                                              Func<int, 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, pagingInfo.ItemsPerPage));

                tag.InnerHtml = i.ToString();

                if (i == pagingInfo.CurrentPage)
                    tag.AddCssClass("selected");
                result.AppendLine(tag.ToString());
            }
            return MvcHtmlString.Create(result.ToString());
        }

我现在调用该函数如下:

Page: @Html.PageLinks( ViewBag.Paging as PagingInfo, (i, j) => Url.Action("Index", new{pageNo = i, pageSize= j}))  

It works a treat now.  Must RTFM more.  Thanks to the Plural Sight videos for helping me resolve this one. 

谢谢,