因項目需要,在苦痛掙扎了一天後,做出了一個返回JSON數據。先放在網上,第一大家看下有什麼地方需要優化沒有,第二是避免其他ASP.Net程序員為網上苦苦搜索而找不到相關代碼而郁悶。
第一步:為了使服務器端查詢返回JSON數據,從網上找了個用C#寫的JSONHelper類(在此感謝那位不知名的好人),以下是JsonHelper類全部代碼。(JSonHelper.cs)
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using System.Web.Script.Serialization;
- /// <summary>
- /// JSONHelper 的摘要說明
- /// </summary>
- public class JSONHelper
- {
- //對應JSON的singleInfo成員
- public string singleInfo = string.Empty;
- protected string _error = string.Empty;
- protected bool _success = true;
- protected long _totalCount = 0;
- protected System.Collections.ArrayList arrData = new ArrayList();
- protected System.Collections.ArrayList arrDataItem = new ArrayList();
- public JSONHelper()
- {
- }
- public static string ToJSON(object obj)
- {
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- return serializer.Serialize(obj);
- }
- public static string ToJSON(object obj, int recursionDepth)
- {
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- serializer.RecursionLimit = recursionDepth;
- return serializer.Serialize(obj);
- }
- //對應於JSON的success成員
- public bool success
- {
- get
- {
- return _success;
- }
- set
- {
- //如設置為true則清空error
- if (success) _error = string.Empty;
- _success = value;
- }
- }
- //對應於JSON的error成員
- public string error
- {
- get
- {
- return _error;
- }
- set
- {
- //如設置error,則自動設置success為false
- if (value != "") _success = false;
- _error = value;
- }
- }
- public long totlalCount
- {
- get { return _totalCount; }
- set { _totalCount = value; }
- }
- //重置,每次新生成一個JSon對象時必須執行該方法
- public void Reset()
- {
- _success = true;
- _error = string.Empty;
- singleInfo = string.Empty;
- arrData.Clear();
- arrDataItem.Clear();
- }
- public void AddItem(string name, string value)
- {
- arrData.Add("\"" + name + "\":" + "\"" + value + "\"");
- }
- public void ItemOk()
- {
- arrData.Add("<BR>");
- }
- //序列化JSON對象,得到返回的JSON代碼
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("{");
- sb.Append("totalCount:" + totlalCount.ToString() + ",");
- sb.Append("success:" + _success.ToString().ToLower() + ",");
- sb.Append("error:\"" + _error.Replace("\"", "\\\"") + "\",");
- sb.Append("singleInfo:\"" + singleInfo.Replace("\"", "\\\"") + "\",");
- sb.Append("data:[");
- int index = 0;
- sb.Append("{");
- if (arrData.Count <= 0)
- {
- sb.Append("}]");
- }
- else
- {
- foreach (string val in arrData)
- {
- index++;
- if (val != "<BR>")
- {
- sb.Append(val + ",");
- }
- else
- {
- sbsb = sb.Replace(",", "", sb.Length - 1, 1);
- sb.Append("},");
- if (index < arrData.Count)
- {
- sb.Append("{");
- }
- }
- }
- sbsb = sb.Replace(",", "", sb.Length - 1, 1);
- sb.Append("]");
- }
- sb.Append("}");
- return sb.ToString();
- }
- }
第二步:新建ASPX文件,做為服務器端,用返回查詢的JSON數據(PagingRequest.cs)
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClIEnt;
- using System.Text;
- namespace ExtJSDemo.Data
- {
- public partial class PagingRequest : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- int start = Convert.ToInt32(Request["start"].ToString()); // ExtJS Paging 必須指定的參數(從第幾行記錄開始)/ ExtJS默認0是第一行記錄
- int limit = Convert.ToInt32(Request["limit"].ToString()); // ExtJS Paging 必須指定的參數(每頁顯示多少行記錄)
- JSONHelper JSonHelp = new JSONHelper();
- int TotalRecords = 0;
- DataSet DSet = GET_Product_Data(start, limit, out TotalRecords); // 獲取數據
- JSonHelp.success = true;
- JSonHelp.totlalCount = TotalRecords;// 記錄總數
- if (DSet != null)
- {
- DataTable DTable = DSet.Tables[0];
- for (int i = 0; i < DTable.Rows.Count; i++)
- {
- // 循環生成JSON代碼
- JSonHelp.AddItem("Id", DTable.Rows[i]["Id"].ToString());
- JSonHelp.AddItem("Name", DTable.Rows[i]["Name"].ToString());
- JSonHelp.AddItem("StreetPrice", DTable.Rows[i]["StreetPrice"].ToString());
- JSonHelp.AddItem("TypeName", DTable.Rows[i]["TypeName"].ToString());
- JSonHelp.ItemOk();
- }
- }
- Response.Write(jsonHelp.ToString()); // 輸出JSON代碼
- }
- /// <summary>
- /// 獲取數據
- /// </summary>
- /// <param name="PageIndex">記錄索引</param>
- /// <param name="PageSize">每頁顯示記錄數</param>
- /// <param name="TotalRecords">總記錄數</param>
- public DataSet GET_Product_Data(int start, int limit,out int TotalRecords)
- {
- SqlConnection _Connection = null;
- SqlDataAdapter _Adapter = null;
- DataSet DSet = null;
- try
- {
- _Connection = new SqlConnection(System.Configuration.ConfigurationManager.APPSettings["SQLContionString"].ToString());
- _Connection.Open();
- _Adapter = new SqlDataAdapter("SELECT [Id] FROM [Product] ",_Connection);
- DSet = new DataSet();
- _Adapter.Fill(DSet);
- TotalRecords = Convert.ToInt32(DSet.Tables[0].Rows.Count); // 記錄總數
- if (TotalRecords < 1) return null; // 沒有記錄
- int pageLowerBound = start+1; // 從第幾條數據開始
- int pageUpperBound = pageLowerBound + limit; // 每頁多少條數據
- StringBuilder sb = new StringBuilder();
- if (TotalRecords >= pageLowerBound)
- {
- for (int i = pageLowerBound; i < TotalRecords && i < pageUpperBound; i++)
- {
- sb.AppendFormat("'{0}',", DSet.Tables[0].Rows[i-1][0].ToString());//構造ID in() 條件,取其中一頁
- }
- }
- else
- return null; // 沒有記錄
- if (sb.Length > 1)
- sb.Remove(sb.Length - 1, 1);//刪除最後一個逗號
- StringBuilder strSql = new StringBuilder();
- strSql.Append("SELECT a.[Id],a.[Name],a.[StreetPrice],b.TypeName ");
- strSql.Append(" FROM [Product] as a left join ProductType as b on a.Typeid = b.Typeid ");
- strSql.AppendFormat(" where a.[Id] in({0})", sb.ToString());
- _Adapter = new SqlDataAdapter(strSql.ToString(), _Connection);
- DSet = new DataSet();
- _Adapter.Fill(DSet);
- }
- finally
- {
- if (_Connection != null && _Connection.State == ConnectionState.Open)
- {
- _Connection.Close();
- }
- }
- return DSet;
- }
- }
- }
第三步:返回JSON數據頁面用作客戶端呈現結果的載體(PagingControls.ASPx)
- <head id="Head1" runat="server">
- <title></title>
- <link rel="stylesheet" type="text/CSS" href="../ext3/resources/css/ext-all.CSS" mce_href="ext3/resources/css/ext-all.CSS" />
- <mce:script type="text/Javascript" src="../ext3/adapter/ext/ext-base.JS" mce_src="ext3/adapter/ext/ext-base.JS"></mce:script>
- <mce:script type="text/Javascript" src="../ext3/ext-all.JS" mce_src="ext3/ext-all.JS"></mce:script>
- <mce:script type="text/Javascript" src="JS/PagingGridPanel.JS" mce_src="JS/PagingGridPanel.JS"></mce:script>
- <mce:script type="text/Javascript"><!--
- Ext.BLANK_IMAGE_URL = "../ext3/resources/images/default/s.gif";
- Ext.onReady(function() {
- Ext.QuickTips.init();
- Ext.form.FIEld.prototype.msgTarget = "side";
- new PagingGridPanel(); // JS文件
- });
- // --></mce:script>
第四部:當然是寫JS腳本啦!!而且肯定使用返回JSON數據