在Asp.net MVC使用jqGrid--代碼少點再少點

來源:互聯網
上載者:User

標籤:read   輸出   produced   meta   pat   nav   name   his   field   

本樣本顯示了如何動態產生前端jqGrid代碼,一般情況僅一行代碼:

<%=Html.jqGrid<TestModel>(@"#jqT", "Test", "/Home/GridData/")%>

效果如下:

 

還不僅僅如此,利用MetaData,將自動對不同實體物件進行捆綁,自動產生Grid。

 

如果你想知道如何在asp.net MVC中使用jqGrid,請參考

http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx

看代碼

1、 擴充HtmlHelper來輸出一段Javascript到用戶端。

 

 

代碼public static class jqGridExtensions
    {
        public static string jqGrid<T>(this HtmlHelper helper, string gridID, string caption, string url)
        {
            if (gridID.Substring(0, 1) != "#")
                gridID = "#" + gridID;
            string pagerID = string.Format("{0}_pager", gridID);
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(" <script type=\"text/javascript\">$(function(){");//jQuery(document).ready(function() {
            sb.AppendLine("$(‘%%GRIDID%%‘).jqGrid({".Replace("%%GRIDID%%", gridID));       //jQuery("#list").jqGrid({
            sb.AppendFormat("url:‘{0}‘,", url);                            //        url: ‘/Home/GridData/‘,
            sb.Append("datatype: ‘json‘,mtype: ‘GET‘,");                 //        datatype: ‘json‘,mtype: ‘GET‘,
            sb.AppendFormat("colNames:[{0}],", GetColNames<T>());

            sb.AppendFormat("colModel:[{0}],", GetColModel<T>());
            sb.Append("pager: ‘%%GRIDPAGERID%%‘,rowNum: 20,rowList: [10, 20, 50,100],".Replace("%%GRIDPAGERID%%", pagerID));
            sb.AppendFormat("sortname:‘{0}‘,sortorder: ‘desc‘,", GetSortField<T>());
            sb.Append("viewrecords: true,imgpath: ‘/themes/redmond/images‘,");
            sb.AppendFormat("caption: ‘{0}‘", caption);
            sb.Append("});\n$(‘%%GRIDID%%‘).jqGrid(‘navGrid‘,‘%%GRIDPAGERID%%‘,{ edit: false, add: false, del: false });".Replace("%%GRIDID%%", gridID).Replace("%%GRIDPAGERID%%", pagerID));
            sb.Append("});</script>\n");
            sb.AppendFormat("<table id=\"{0}\" class=\"scroll\" cellpadding=\"0\" cellspacing=\"0\"></table>", gridID.Substring(1));
            sb.AppendFormat("<div id=\"{0}\" class=\"scroll\" style=\"text-align:center;\"></div>", pagerID.Substring(1));
            sb.AppendLine();
            return sb.ToString();
        }
}

 

上述代碼隱含了3個函數來取得排序欄位,Grid的欄位標題及ColModel。

 

2、 對Grid的欄位標題及排序欄位,ColModel進行定製。以GetColModel為例:

 

 

代碼 private static string GetColModel<T>()
        {
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));

            StringBuilder sb = new StringBuilder();
            int width=100;
            foreach (ModelMetadata proMeta in metadata.Properties)
            {
                ColWidthAttribute colWidthAttr = GetCustomAttribute<ColWidthAttribute>(proMeta) as ColWidthAttribute;
                if (colWidthAttr != null)
                    width = colWidthAttr.Width;
                sb.Append("{");
                sb.AppendFormat("name:‘{0}‘,index:‘{0}‘,width:{1},align:‘left‘", proMeta.PropertyName, width);
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
            //return "{ name: ‘Id‘, index: ‘Id‘, width: 140, align: ‘left‘ }, { name: ‘Votes‘, index: ‘Votes‘, width: 180, align: ‘left‘ },{ name: ‘Title‘, index: ‘Title‘, width: 400, align: ‘left‘,editable:true}";
        }

        private static object GetCustomAttribute<T>(ModelMetadata proMeta) 
        {
            PropertyInfo property = proMeta.ContainerType.GetProperty(proMeta.PropertyName);
            object[] propertyAttributes = property.GetCustomAttributes(typeof(T), true);
            if (propertyAttributes.Length > 0)
            {
                return (propertyAttributes[0]);

            }
            
            return null;
        }

 

 

3、 擴充一個列寬(Column Width)屬性。

 

 

 public class ColWidthAttribute: Attribute
    {
        public ColWidthAttribute()
        {

        }

        public int Width { get; set; }
    }

 

 

 

 

4、 如何定製實體物件。

 

代碼    [DisplayName("ID")]//暫時用這個來表示排序欄位
    public class TestModel
    {
        [DisplayName("編號")]
        [ColWidth(Width=100)]
        public int ID{get;set;}

        [DisplayName("支援率")]
        [ColWidth(Width = 120)]
        public int Votes { get; set; }

        [DisplayName("議題")]
        [ColWidth(Width = 300)]
        public string Title { get; set; }

    }

 

 

 

5、 Controller中的代碼。

 

 

代碼 public ActionResult GridData(string sidx, string sord, int page, int rows)
        {
            var jsonData = new
            {
                total = 1, // we‘ll implement later 
                page = page,
                records = 3, // implement later 
                rows = new[]{
                      new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
                      new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
                      new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
                }
            };
            return Json(jsonData,JsonRequestBehavior.AllowGet);
        }

 

千萬要記得JSon中設定JsonRequestBehavior.AllowGet,否則jqGrid中將只有表頭沒有資料。

6、 前端代碼。

 

 

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

<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
    About Us
</asp:Content>

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>About</h2>
    <p>
        Put content here.
    </p>
    <div>
    
    <%=Html.jqGrid<TestModel>(@"#jqT", "Test", "/Home/GridData/")%>
    </div>
</asp:Content>

 

看完,也許你會說這還叫代碼少一點,我只是覺得這篇文章可能浪費你的時間。

看完,也許你覺得這個例子威力太小,還想要能夠自動支援在jqGrid上是否能夠編輯,以及子表支援,等等~~~,我就覺得很欣慰了。

 

在Asp.net MVC使用jqGrid--代碼少點再少點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.