接上一篇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字符串

其代码如下:

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格式的字符串,其代码如下:

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();
        }


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" />

 

相关文章:

  • 2021-05-31
  • 2022-02-17
  • 2021-05-26
  • 2021-11-13
  • 2022-02-28
  • 2022-12-23
  • 2021-04-12
  • 2021-11-23
猜你喜欢
  • 2021-09-12
  • 2021-12-26
  • 2022-01-24
  • 2021-09-28
  • 2022-02-19
  • 2022-02-28
  • 2022-02-23
相关资源
相似解决方案