すらいむがあらわれた

こまんど >  たたかう  にげる

FlexiGrid + ASP.NET MVC

http://flexigrid.info/
ほぼサンプルのjavascriptを張るだけでなかなかかっこいい表ができます。
公式サイトにドキュメントがほとんどない。でもそれで使えてしまうほどシンプル。

FlexiGrid
FlexiGrid posted by (C)kanpan

Controller側

        private string conStr = ConfigurationManager.ConnectionStrings["TepcoConnectionString"].ConnectionString;

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FlexiGrid()
        {
            return View();
        }

        private int GetTotalCount()
        {
            int count = 0;

            using (SqlConnection sqlCon = new SqlConnection(conStr))
            {
                try
                {
                    sqlCon.Open();

                    String sql = "select count(*) from usage";

                    SqlCommand command = new SqlCommand(sql, sqlCon);

                    count = (int)command.ExecuteScalar();

                }
                catch (Exception)
                {
                    count = 0;
                }
            }
            return count;
        }

        public ActionResult UseFlexiGrid(
            int page, 
            int rp,
            string sortname, 
            string sortorder,
            string query,
            string qtype
            )
        {

            int total = GetTotalCount();

            using (SqlConnection sqlCon = new SqlConnection(conStr))
            {
                try
                {
                    sqlCon.Open();

                    String sql = String.Join(" ", new string[]
                        {
                        "select *",
                        "	from ( ",
                        "		select ROW_NUMBER() over (order by " + sortname + " " + sortorder + ") as rn,  *",
                        "		from usage",
                        "	) as TMP",
                        "	where TMP.rn > @p0 and TMP.rn <= @p1",
                        }
                            );

                    if (String.IsNullOrEmpty(qtype) == false
                        && String.IsNullOrEmpty(query) == false)
                    {
                        sql += " and ";
                        sql += qtype + "= @query";
                    }

                    SqlCommand command = new SqlCommand(sql, sqlCon);
                    command.Parameters.Add("@p0", SqlDbType.Int).Value = (page - 1) * rp;
                    command.Parameters.Add("@p1", SqlDbType.Int).Value = page * rp;

                    if (String.IsNullOrEmpty(qtype) == false
                        && String.IsNullOrEmpty(query) == false)
                    {
                        command.Parameters.Add("@query", SqlDbType.Int).Value = Convert.ToInt32(query);
                    }

                    SqlDataReader reader = command.ExecuteReader();

                    List<object> rowList = new List<object>();

                    while (reader.Read())
                    {
                        long recNo = reader.GetInt64(1);
                        int year = reader.GetInt32(2);
                        int month = reader.GetInt32(3);
                        int day = reader.GetInt32(4);
                        int hour = reader.GetInt32(5);

                        int capacity = reader.GetInt32(7);
                        int usage = reader.GetInt32(10);


                        rowList.Add(new { id = recNo, cell = new object[] { year, month, day, hour, capacity, usage } });
                    }

                    if (Request.IsAjaxRequest())
                    {
                        JsonResult result = Json(
                            new
                            {
                                page = page,
                                total = total,
                                rows =
                                rowList.ToArray(),
                            }
                            );

                        return result;
                    }
                    else
                    {
                        this.Response.StatusCode = 403;
                        return new EmptyResult();
                    }
                }
                catch (Exception ex)
                {
                    this.Response.StatusCode = 500;
                    return new EmptyResult();
                }

            }
        }

View側

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	FlexiGrid
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>FlexiGrid</h2>
    <table id="flex1"></table>

    <script src="<%= ResolveClientUrl("~/Scripts/flexigrid/flexigrid.js")  %>" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#flex1").flexigrid
			(
			{
			    url: '<%: ResolveClientUrl("~/Main/UseFlexiGrid") %>',
			    dataType: 'json',
			    colModel: [
				{ display: '年', name: 'year', width: 40, sortable: true, align: 'center' },
				{ display: '月', name: 'month', width: 40, sortable: true, align: 'left' },
				{ display: '日', name: 'day', width: 40, sortable: true, align: 'left' },
				{ display: '時', name: 'hour', width: 40, sortable: true, align: 'left' },
                { display: '供給可能(万kW)', name: 'capacity', width: 80, sortable: true, align: 'right' },
				{ display: '使用量(万kW)', name: 'usage', width: 80, sortable: true, align: 'right' }
				],
			    sortname: "usage",
			    sortorder: "desc",
			    usepager: true,
			    singleSelect: true,
			    title: '東京電力電力使用量',
			    useRp: true,
			    rp: 5,
			    showTableToggleBtn: true,
			    width: 700,
			    height: 200
			}
			);
        });
	
    </script>

</asp:Content>

英文ですがこちらに良い紹介記事があります。
私が書いたのはSQLをベタに呼んでますが、こちらではLINQを使用してます。
ASP.NET MVC Flexigrid sample - THE CODE PROJECT
http://www.codeproject.com/KB/aspnet/MVCFlexigrid.aspx