陈斌彬的技术博客

Stay foolish,stay hungry

NET后台返回JSON数据类

CS文件代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        string sql = "select * from Ext";
        //获取记录数
        int SqlCount=SqlHelp.DataBySQL.GetRowCount(sql);
        Public.JSONHelper json = new Public.JSONHelper();
        json.success = true;
        json.totlalCount = SqlCount;
        SqlDataReader reader = SqlHelp.DataBySQL.GetDataReader(sql);
        while (reader.Read())
        {
            json.AddItem("id",reader["id"].ToString());
            json.AddItem("name",reader["name"].ToString());
            json.AddItem("sex", reader["sex"].ToString());
            json.ItemOk();
        }
        reader.Close();
        //返回Json格式数据
        Info = json.ToString();
    }

返回内容:

{totalCount:4,success:true,error:"",singleInfo:"",data:[{"id":"1","name":"tianzhi","sex":"男"},{"id":"2","name":"tianzhi2","sex":"男"},{"id":"3","name":"tianzhi3","sex":"男"},{"id":"4","name":"tianzhi5","sex":"男"}]}

前台代码:

 Ext.onReady(function() {
    //为防止去官网下载图片
    Ext.BLANK_IMAGE_URL = 'ExtJs/resources/images/default/s.gif';
    //数据
    var data = new Ext.data.HttpProxy({ url: "JSONHelper.aspx" });
    //解析内容
    var reader = new Ext.data.JsonReader({
        root: "data",
        id: "id",
        totalProperty: "totalCount",
        successProperty: "success"
    }, [
            { name: "id", mapping: "id" },
            { name: "name", mapping: "name" },
            { name: "sex", mapping: "sex" }
        ]);
            //填充数据
            var store = new Ext.data.Store({
                proxy: data,
                reader: reader
            });
            store.load();
            //多选按钮
            var check = new Ext.grid.CheckboxSelectionModel();
            //Grid的表头
            var cm = new Ext.grid.ColumnModel([
             new Ext.grid.RowNumberer(), //Grid的序号
             check, //多选框
             {header: "编号", dataIndex: "id" },
             { header: "姓名", dataIndex: "name" },
             { header: "性别", dataIndex: "sex" }
        ]);
            //Grid内容
            var gg = new Ext.grid.GridPanel({
                el: "grid", //要显示的位置
                ds: store, //数据内容
                cm: cm, //表头
                height: 200, //高
                width: 400, //宽
                title: "第一个例子",
                sm: check //添加多选按钮的地方
            });
            gg.render();

    //尾部
    });

数据库角本(SQL2005):

CREATE TABLE [dbo].[Ext](
 [id] [int] NULL,
 [name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 [sex] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

JSONHelper类文件:

 public class JSONHelper
  {
      protected System.Collections.ArrayList arrData = new System.Collections.ArrayList();
      public string singleInfo = string.Empty;
      protected string _error = string.Empty;
      protected bool _success = true;
      protected long _totalCount = 0;
      public void AddItem(string name, string value)
      {
          arrData.Add("\"" + name + "\":" + "\"" + value + "\"");
      }
      public void ItemOk()
      {
          arrData.Add("<BR>");
      }
      #region 设置success为TURE,代表成功
      public bool success
      {
          get
          {
              return _success;
          }
          set
          {
              //如设置为true则清空error
              if (success) _error = string.Empty;
              _success = value;
          }
      }
      #endregion

      public long totlalCount
      {
          get { return _totalCount; }
          set { _totalCount = value; }
      }
      //序列化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
                  {
                      sb = sb.Replace(",", "", sb.Length - 1, 1);
                      sb.Append("},");
                      if (index < arrData.Count)
                      {
                          sb.Append("{");
                      }
                  }
              }
              sb = sb.Replace(",", "", sb.Length - 1, 1);
              sb.Append("]");
          }
          sb.Append("}");
          return sb.ToString();
      }
  }