封裝jQuery表格外掛程式jqGrid,控制項化jqGrid(二):顯示

來源:互聯網
上載者:User

接上一篇http://www.cnblogs.com/bestfc/archive/2010/06/07/1753216.html

本文編碼資料提供類

1,建立AjaxData類,繼承介面IHttpHandler,實現其方法public void ProcessRequest(HttpContext context)和參數public bool IsReusable

2,使用SqlHelper類與資料庫進行互動(在MVC中可以使用entity framework提供資料,當然在MVC中,最好就不要使用伺服器控制項了,可以直接輸出字串)

3,在AjaxData類中,建立兩個方法

public string jsonString(HttpContext context)用於處理接收到的基本資料,最後經過以下方法返回資料的json字串

其代碼如下:

 public string jsonString(HttpContext context)        {            //params from Request.QueryString            string tableName = context.Request.QueryString["tablename"].ToString();            string xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + tableName + ".xml";            int _currentPage = int.Parse(context.Request.QueryString["page"].ToString());    // get the context.Requested page            int _pageStep = int.Parse(context.Request.QueryString["rows"].ToString());     // get how many rows we want to have into the grid            string sidx = context.Request.QueryString["sidx"].ToString();        // get index row - i.e. user click to sort            string sord = context.Request.QueryString["sord"].ToString();      // get the direction            //params from XML            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.Load(xmlPath);            XmlNode xnRoot = xmlDoc.SelectSingleNode("root");            string fields = xnRoot.Attributes["fields"].Value;            string fixCondition = string.Empty;                            //固ì定¨條?件t            if (xnRoot.Attributes["fixCondition"] != null) fixCondition = xnRoot.Attributes["fixCondition"].Value;            DataTable dt = SqlHelper.GetDataByPager(fields, tableName, " 1=1 " + fixCondition + searchCase, sidx + " " + sord, (_currentPage - 1), _pageStep);            int _recordCount = SqlHelper.GetRecordCount(tableName, " 1=1 " + fixCondition + searchCase);            int _totalPages;            if (_recordCount % _pageStep == 0)            {                _totalPages = _recordCount / _pageStep;            }            else            {                _totalPages = _recordCount / _pageStep + 1;            }            if (_recordCount == 0)            {                return string.Empty;            }            else            {                return DataTableToJson(dt, _currentPage, _totalPages, _recordCount, xmlDoc);            }        }

 

其中使用到了SqlHelper.cs提供的SQL2005預存程序。

public string DataTableToJson(DataTable dt, int page, int total, int records, XmlDocument xmlDoc)用於DataTable轉化為jqGrid格式的字串,其代碼如下:

public string DataTableToJson(DataTable dt, int page, int total, int records, XmlDocument xmlDoc)        {            XmlNodeList xnList = xmlDoc.SelectNodes("root//columns");            string idKey = string.Empty;            foreach (XmlNode xn in xnList)            {                if (xn.Attributes["IsIdentity"] != null)                {                    idKey = xn.Attributes["name"].Value;                }            }            StringBuilder sb = new StringBuilder();            sb.Append("{");            sb.Append("\"page\":" + page + ",");            sb.Append("\"total\":" + total + ",");            sb.Append("\"records\":" + records + ",");            //-----------rows build            sb.Append("\"rows\":[");            foreach (DataRow dr in dt.Rows)            {                sb.Append("{\"id\":\"" + dr[idKey] + "\",");                sb.Append("\"cell\":[");                //-----------columns build                foreach (XmlNode xn in xnList)                {                    if (xn.Attributes["name"].Value != idKey)                    {                        string values = dr[xn.Attributes["name"].Value].ToString();                        if (values.IndexOf("\n") >= 0)  //解決JSON字串含斷行符號時的“未終止的字串常量”問題                        {                            values = values.Replace("\n", "\\n");                        }                        else if (values.IndexOf('"') >= 0)  //解決"造成json字串斷層的問題,使用中文的”解決或單引號解決                        {                            values = values.Replace('"', '“°');                        }                        if (xn.Attributes["sorttype"] != null)                        {                            switch (xn.Attributes["sorttype"].Value)                            {                                case "data":                                    if (dr[xn.Attributes["name"].Value] != DBNull.Value)                                    {                                        sb.Append("\"" + DateTime.Parse(values) + "\",");                                    }                                    else                                    {                                        sb.Append("\" \",");                                    }                                    break;                                case "float":                                    if (dr[xn.Attributes["name"].Value] != DBNull.Value)                                    {                                        sb.Append("\"" + Decimal.Parse(values).ToString("0.00") + "\",");                                    }                                    else                                    {                                        sb.Append("\" \",");                                    }                                    break;                                default:                                    sb.Append("\"" + values + "\",");                                    break;                            }                        }                        else                        {                            sb.Append("\"" + values + "\",");                        }                    }                }                sb.Remove(sb.Length - 1, 1);                //-----------end columns build                sb.Append("]");                sb.Append("},");            }            sb.Remove(sb.ToString().Length - 1, 1);            sb.Append("]");            //----------end rows build            sb.Append("}");            return sb.ToString();        }


從以上兩個方法可以看到,傳過來的值中,自訂了一個QueryString,tablename用於取得對應的設定檔,也可以使用反射的方法去提供資料,但是相對於來說,很不靈活。

4,在ProcessRequest方法中編碼對於前台的動作反饋相應的資料,以下是部分代碼:

if (context.Request.QueryString["action"] != null)            {                string actions = context.Request.QueryString["action"].ToString();                switch (actions)                {                    case "view":                            context.Response.Write(jsonString(context));

傳過來的值中,自訂了一個QueryString,action用於判別前台傳過來的動作,用於後面還有的查詢,編輯,修改,刪除等功能。

這裡只反饋資料用於前台的顯示。

 

這樣,AjaxData完成。

接下來可以建立一個前台項目,為中上面的方法中擷取資料,在web.config聲明httpHandlers:

<httpHandlers>        <add path="data.ashx" verb="*" type="AspJqGrid.AjaxData,AspJqGrid"/>      </httpHandlers>

 

位於system.web節點下,這樣,就將頁面請求定位到了AspJqGrid的AjaxData類

另外,在控制項代碼中加入了[assembly:TagPrefix("AspJqGrid","AllenJqGrid")],在web.config中聲明全域

<pages>        <controls>          <add tagPrefix="AllenJqGrid" assembly="AspJqGrid" namespace="AspJqGrid" />        </controls>      </pages>

第一步的Hello World顯示方面的工作就完成了,下一篇開始編碼查詢功能

這樣,在頁面中添加<AllenJqGrid:JqGrid ID="MyJqGrid" runat="server" TableName="diamond" />

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.