我的ASP.NET MVC实践系列
ASP.NET MVC实践系列1-UrlRouting 
ASP.NET MVC实践系列2-简单应用 
ASP.NET MVC实践系列3-服务器端数据验证 
ASP.NET MVC实践系列4-Ajax应用 
ASP.NET MVC实践系列5-结合jQuery 
ASP.NET MVC实践系列6-Grid实现(上) 
 
其他:
在ASP.NET MVC中对表进行通用的增删改 
很多情况下我们展示数据都是通过网格来做的,在webform中我们常使用GridView或ListView,实际上简单实现这些网格也并不困难,上节讲了在mvc中Grid的简单实现,但是如果很多页面都要使用网格来显示,每次都要写循环的td,tr就有点麻烦了,当然在mvc中我们可以继续使用GridView或ListView,但是使用的时候很多地方很蹩脚,这里我们可以利用Helper的方式来封装这个过程。Mvc Contrib中帮我们实现好了一套Grid,所以这里我不重新搞个新的了,Contrib的源码可以到http://www.codeplex.com/MVCContrib 中下载
一、准备工作
1、准备一个模拟类和类的集合

 模拟类
模拟类
public class News
{
    public int ID { get; set; }
    public string Author { get; set; }
    public string Title { get; set; }
    public DateTime CreateTime { get; set; }
}
public class ListNews
{
    public static List<News> GetList()
    {
        List<News> list = new List<News>();
        list.Add(new News { ID = 1, Author = "lfm1", Title = "中华人民共和国60周年", CreateTime = DateTime.Now });
        list.Add(new News { ID = 2, Author = "lfm2", Title = "中华人民共和国61周年", CreateTime = DateTime.Now.AddHours(1) });
        list.Add(new News { ID = 3, Author = "lfm3", Title = "中华人民共和国62周年", CreateTime = DateTime.Now.AddHours(2) });
        list.Add(new News { ID = 4, Author = "lfm3", Title = "中华人民共和国63周年", CreateTime = DateTime.Now.AddHours(3) });
        list.Add(new News { ID = 5, Author = "lfm2", Title = "中华人民共和国64周年", CreateTime = DateTime.Now.AddHours(4) });
        return list;
    }
}2、为了在View中输入时不用每页使用<%@ Import Namespace="MvcContrib.UI.Grid" %>导入命名空间,我们需要在webconfi的<pages>中输入如下:
 

 webconfig配置
webconfig配置
        <pages>
            <namespaces>
                <add namespace="System.Collections.Generic"/>
                <add namespace="MvcContrib.UI.Grid"/>
        <add namespace="MvcContrib.UI.Pager"/>
        <add namespace="MvcContrib.Pagination"/>
            </namespaces>
        </pages> 
二、简单应用
在View中输入 <%=Html.Grid(Model).AutoGenerateColumns() %>,Grid根据Model中的内容反射得到相应的列和行,非常简单,但并不实用。一般我们需要定义需要显示的列:
View

 View
View
<%=Html.Grid(Model).Columns(column=>{
    column.For(x=>x.ID).Named("News ID");
    column.For(x => Html.ActionLink(x.Title, "NewsDetils", new { newsId = x.ID })).DoNotEncode();
    column.For(x => x.Author);
    column.For(x=>x.CreateTime);
})
    %>Columns的参数是一个Action<ColumnBuilder<T>的委托,Grid方法会利用你传入的这个委托来帮你处理表格显示。column.For是用来处理每个列的,Named用来重新标示列名,如果不使用Named,列名直接为For参数的ToString()内容。默认情况下列中显示的内容都会被编码,所以如果不需要编码则需要使用DoNotEncode()方法。
 三、分页显示
1、简单分页:
View:

 View
View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IPagination<News>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ListPager
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%=Html.Grid(Model).Columns(column=>{
    column.For(x=>x.ID).Named("News ID");
    column.For(x => Html.ActionLink(x.Title, "NewsDetils", new { newsId = x.ID })).DoNotEncode();
    column.For(x => x.Author);
    column.For(x=>x.CreateTime);
})
    %>
<%= Html.Pager(Model)%>
</asp:Content>
这里需要注意Inherits="System.Web.Mvc.ViewPage<IPagination<News>>" ,这个强类型是用于分页的
Controller:
        public ActionResult ListPager(int? page)
        {
            var pagedNews = ListNews.GetList().AsPagination(page.GetValueOrDefault(1), 5);
            return View(pagedNews);
        }
这里不要忘了要引入命名空间MvcContrib.Pagination;
这个AsPagination是IEnumerable<T>的扩展方法,是将实现了IEnumerable的集合类转换成IPagination<T>
2、自定义分页
上面的那个简单分页实现起来很容易,但对于大数据量的情况往往性能不佳,所以我们常常要自定义分页,contrib中也很好的支持了自定义分页

 自定义分页代码
自定义分页代码
      public ActionResult CustomPager(int? page)
        {
            int pageSize=5;
            int pageNumber = page ?? 1;
            var list = ListNews.GetList().Skip((pageNumber-1) * pageSize).Take(pageSize);
            int total = ListNews.GetList().Count;
            CustomPagination<News> customes = new CustomPagination<News>(list, pageNumber, pageSize, total);
            return View(customes);
        }3、分页中有用的属性
默认分页的页面展示如下:

估计这不会是你想要的分页格式,下面我们自定义一下这个分页 
将分页输出改为: 
<%= Html.Pager(Model).First("第一页").
    Last("最后一页").Previous("上一页").Next("下一页").Format("当前为从{0}行到{1}行,总{2}行,") %>
会得到如下结果:
默认情况下有两个class可控制。
四、颜色分隔
View:

 行颜色分隔代码
行颜色分隔代码
<%Html.Grid(Model).Columns(column =>
  {
      column.For(x => x.ID).Named("News ID");
      column.For(x => Html.ActionLink(x.Title, "NewsDetils", new { newsId = x.ID })).DoNotEncode();
      column.For(x => x.Author);
      column.For(x => x.CreateTime);
  }).RowStart((p, row) =>
            {
                if (row.IsAlternate)
                {
                    %><tr style="background-color:#CCDDCC"><%
                                                           
    }
                else
                {
                    %><tr><%
                    
    }
            }
         ).Render(); %>要注意的是这里要引入<%@ Import Namespace="MvcContrib.UI.Grid.ActionSyntax" %>命名空间
五、排序
1、默认排序
contrib的grid中默认排序很简单
你希望按哪列排序就改写那列
column.For(x => x.Author).Sortable(true);
但这种排序可能不符合你的要求,因为它只会将本Model的数据进行排序,当自定义分页的时候得到的往往不是你想要的结果。
2、自定义排序
可以改写需要排序的列:
    column.For(x => x.Author).Header("<th>"+Html.ActionLink("作者","CustomPager",new{desc = Convert.ToBoolean(ViewData["desc"]),sortName="Author"})+"</th>");
Controller中的做法可以参考ASP.NET MVC实践系列6-Grid实现(上) 
六、其他
参见MvcContrib.Samples.UI,可以在http://www.codeplex.com/MVCContrib 中下载
七、源码下载