Extjs、ASP.net前後臺Grid分頁 數據庫多表交互

1 建立ASP.net Web應用程序
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客


2 在App_Data文件夾內建立數據庫db_test
 
     Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客
 
建立2張表,通過use_id的外鍵找出‘這個學生的成績’

3 插入一些數據,數據可以自定義
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客
  

4 解決方案右鍵,建立類庫Model(此類庫爲數據庫中的表抽象出一個類模型)
 
若:前臺要顯示學生的use_id、use_name 、use_sex、 use_address、 sco_subject、 sco_score。
 

Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客
即建立一個show_score.cs
 

代碼
 using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Model{    public class show_score    {        private int _use_id;        public int use_id           //字段user_id        {            get { return _use_id; }            set { _use_id = value; }        }private string _use_name;        public string use_name      //字段use_name        {            get { return _use_name; }            set { _use_name = value; }        }private string _use_sex;        public string use_sex       //字段use_sex        {            get { return _use_sex; }            set { _use_sex = value; }        }private string _use_address;        public string use_address   //字段use_address        {            get { return _use_address; }            set { _use_address = value; }        }private string _sco_subject;        public string sco_subject   //字段sco_subject        {            get { return _sco_subject; }            set { _sco_subject = value; }        }private int _sco_score;        public int sco_score        {            get { return _sco_score; }            set { _sco_score = value; }        }    }}
5 建立一個公用的服務庫類Service
 
Service中建立DBHelper.cs和show_score_Service.cs
 

Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客
DBHelper.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;//數據庫連接的命名空間using System.Data;//DataSet的命名空間namespace Service{    public class DBHelper    {        private static SqlConnection connection;//創建connection連接對象        public static SqlConnection Conneciton        {            get//get  關鍵字在屬性或索引器中定義訪問器方法,以檢索該屬性或該索引器元素的值。            {                string temp_connectionstring = @"Data Source=./SQLEXPRESS;AttachDbFilename=E:/Asp.net/Extjs、ASP.net前後臺數據交互/Extjs、ASP.net前後臺數據交互/App_Data/db_test.mdf;Integrated Security=True;User Instance=True";                if (connection == null)                {                    connection = new SqlConnection(temp_connectionstring);                    connection.Open();                }                //System.Data.ConnectionState描述與數據源的連接的當前狀態。                //Broken    與數據源的連接中斷。只有在連接打開之後纔可能發生這種情況。可以關閉處於這種狀態的連接,然後重新打開。(該值是爲此產品的未來版本保留的。)                  //Closed    連接處於關閉狀態。                 //Connecting    連接對象正在與數據源連接。(該值是爲此產品的未來版本保留的。)                  //Executing    連接對象正在執行命令。(該值是爲此產品的未來版本保留的。)                  //Fetching    連接對象正在檢索數據。(該值是爲此產品的未來版本保留的。)                  //Open    連接處於打開狀態。                 else if (connection.State == System.Data.ConnectionState.Closed)                {                    connection.Open();                }                else if (connection.State == System.Data.ConnectionState.Broken)                {                    connection.Close();                    connection.Open();                }                return connection;            }        }//ExecuteNonQuery,對連接執行 Transact-SQL 語句並返回受影響的行數。        public static int ExecuteCommand(string temp_sql)        {            SqlCommand temp_cmd = new SqlCommand(temp_sql, Conneciton);            int temp_result = temp_cmd.ExecuteNonQuery();            return temp_result;        }//執行查詢,並返回查詢所返回的結果集中第一行的第一列。忽略其他列或行。        public static int GetScalar(string temp_sql)        {            SqlCommand temp_cmd = new SqlCommand(temp_sql, Conneciton);            int temp_result = Convert.ToInt32(temp_cmd.ExecuteScalar());            return temp_result;        }//提供一種從 SQL Server 數據庫讀取行的只進流的方式。        public static SqlDataReader GetReader(string temp_sql)        {            SqlCommand temp_cmd = new SqlCommand(temp_sql, Conneciton);            SqlDataReader temp_reader = temp_cmd.ExecuteReader();            return temp_reader;        }//獲取表的記錄集        public static DataTable GetDataSet(string temp_sql)        {            DataSet temp_ds = new DataSet();            SqlCommand temp_cmd = new SqlCommand(temp_sql, Conneciton);            SqlDataAdapter temp_da = new SqlDataAdapter(temp_cmd);            temp_da.Fill(temp_ds);            return temp_ds.Tables[0];        }    }}
show_score_Service.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Model;//添加完程序引用集後,添加命名空間using System.Data.SqlClient;namespace Service{    public class show_score_Service    {        public List<show_score> GetAllUser()        {            string temp_str = "select A.use_id,use_name," +            "use_sex,use_address,sco_subject,sco_score from tb_user A,tb_score B A.use_id=B.use_id";            List<show_score> temp_list = new List<show_score>();            temp_list = GetBySql(temp_str, null);            if (temp_list.Count > 0) { return temp_list; }            else { return null; }        }private static List<show_score> GetBySql(string temp_sql, SqlParameter[] temp_values)        {            using (SqlDataReader temp_reader = DBHelper.GetReader(temp_sql))            {                List<show_score> temp_list = new List<show_score>();                show_score temp_user = null;                while (temp_reader.Read())                {                    temp_user = new show_score();                    temp_user.use_id = int.Parse(temp_reader["use_id"].ToString());                    temp_user.use_name = temp_reader["use_name"].ToString();                    temp_user.use_sex = temp_reader["use_sex"].ToString();                    temp_user.use_address = temp_reader["use_address"].ToString();                    temp_user.sco_subject = temp_reader["sco_subject"].ToString();                    temp_user.sco_score = int.Parse(temp_reader["sco_score"].ToString());                    temp_list.Add(temp_user);                }                temp_reader.Close();                return temp_list;            }        }    }}
6 建立show_grid.aspx,添加 服務庫類Service和類模型Model 的引用和命名空間
 
 show_grid.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Show_grid.aspx.cs" Inherits="ExtJs_vs2008_ASP.net數據交互.Show_grid" %>
show_grid.aspx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Model;//添加命名空間using Service;using System.Data.SqlClient;using System.Web.Script.Serialization;//Json序列化using System.Text;namespace ExtJs_vs2008_ASP.net數據交互{    public partial class Show_grid : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            string temp_json = "";            string temp_type = Request.QueryString["parm"].ToString();            if(temp_type=="List")            {                temp_json = doList();                Response.Write(temp_json);            }        }        private string doList()        {            show_score_Service temp_ser = new show_score_Service();            List<show_score> temp_list = temp_ser.GetAllUser();            JavaScriptSerializer java = new JavaScriptSerializer();            StringBuilder temp_sb = new StringBuilder();            java.Serialize(temp_list, temp_sb);            string temp_json = temp_sb.ToString();            return temp_json;        }    }}
7 需要引入的目錄文件
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客


a.需要分頁,我習慣用PagingMemoryProxy.js(可從ExtJs文件夾內搜索得到)分頁,引入解決方案中
 
b.將ExtJs文件引入解決方案中
 
c.編輯一個my_datagrid.js文件
Ext.onReady(function() {    store = new Ext.data.JsonStore({        data: [],        fields: [                { name: 'use_id' },                { name: 'use_name' },                { name: 'use_sex' },                { name: 'use_address' },                { name: 'sco_subject' },                { name: 'sco_score' }            ]    });    Ext.Ajax.request({                            //讀取後臺傳遞於前臺數據        url: 'Show_grid.aspx?parm=List',        method: 'get',        success: function(response, opts) {            var obj = Ext.decode(response.responseText); //obj 儲存響應的數據            store.proxy = new Ext.data.PagingMemoryProxy(obj), //PagingMemoryProxy() 一次性讀取數據            store.load({ params: { start: 0, limit: 4} }); //按4 條記錄分佈        },        failure: function() { Ext.Msg.alert("failure"); }    });var grid = new Ext.grid.GridPanel({        frame: true,        title:'學生各科成績表',        stripeRows: true, //斑馬線        store: store,        id: 'grid',        applyTo: 'grid',        trackMouseOver: true,        height: 300,        width:500,        loadMask: {msg:'正在加載數據,請稍侯……'},        viewConfig: {            forceFit: true        },        columns: [            new Ext.grid.RowNumberer(), //行號            {header: '<font size=2>用戶帳戶</font>', dataIndex: 'use_id', sortable: true },            { header: '<font size=2>用戶姓名</font>', dataIndex: 'use_name', sortable: true },            { header: '<font size=2>用戶性別</font>', dataIndex: 'use_sex', sortable: true },            { header: '<font size=2>用戶地址</font>', dataIndex: 'use_address', sortable: true },            { header: '<font size=2>考試科目</font>', dataIndex: 'sco_subject', sortable: true },            { header: '<font size=2>考試分數</font>', dataIndex: 'sco_score', sortable: true }        ],        bbar: new Ext.PagingToolbar({//分頁            pageSize:4,            store: store,            displayInfo: true, //非要爲true,不然不會顯示下面的分頁按鈕            displayMsg: '<font size=2>第 {0} 條到 {1} 條,一共 {2} 條記錄</font>',            emptyMsg: "沒有記錄"        })    })})
8 前臺Default.aspx的編寫
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Extjs_ASP.net前後臺數據交互._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><link rel="Stylesheet" type="text/css" href="ExtJs/resources/css/ext-all.css" />    <script type="text/javascript" src="ExtJs/adapter/ext/ext-base.js"></script>    <script type="text/javascript" src="ExtJs/ext-all.js"></script>    <script src="PagingMemoryProxy.js" type="text/javascript"></script>    <script src="my_datagrid.js" type="text/javascript"></script><title>ExtJs與ASP.net前後臺交互</title></head><body>    <form id="form1" runat="server">    <div id="grid"></div>    </form></body></html>
9 運行效果
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客


===========================================================================
 
===========================================================================
 
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客

10 總結
 
a.構造出要顯示的類模型
 
b.添加引用、命名空間、庫類
 
  學習上一些類使用的中文幫助:http://msdn.microsoft.com/zh-cn/library
 
  英文:http://msdn.microsoft.com/en-us/library
 
c.List的泛型類
 
  表示可通過索引訪問的對象的強類型列表。提供用於對列表進行搜索、排序和操作的方法。
 
  命名空間:System.Collections.Generic
  程序集:mscorlib(在 mscorlib.dll 中)
 
  [SerializableAttribute] public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
 
d.JavaScriptSerializer類
 
  JavaScriptSerializer 類由異步通信層內部使用,用於序列化和反序列化在瀏覽器和 Web 服務器之間傳遞的數據。您無法訪問序列化程序的此實例。但是,此類公開了公共 API。因此,當您希望在託管代碼中使用 JavaScript 對象符號 (JSON) 時可以使用此類。

11 備註
 
  讀者看後可能會覺得我寫得複雜了一些,實際操作的話,可以化簡很多。主要還是闡述了以下圖的道理
 
            
 Extjs、ASP.net前後臺Grid分頁 數據庫多表交互 - youzhangcai - 遊仉才的博客
  主要代碼2段片段:


代碼
             using (SqlDataReader temp_reader = DBHelper.GetReader(temp_sql))            {                List<show_score> temp_list = new List<show_score>();                show_score temp_user = null;                while (temp_reader.Read())                {                    temp_user = new show_score();                    temp_user.use_id = int.Parse(temp_reader["use_id"].ToString());                    temp_user.use_name = temp_reader["use_name"].ToString();                    temp_user.use_sex = temp_reader["use_sex"].ToString();                    temp_user.use_address = temp_reader["use_address"].ToString();                    temp_user.sco_subject = temp_reader["sco_subject"].ToString();                    temp_user.sco_score = int.Parse(temp_reader["sco_score"].ToString());                    temp_list.Add(temp_user);                }                temp_reader.Close();                return temp_list;            }            JavaScriptSerializer java = new JavaScriptSerializer();            StringBuilder temp_sb = new StringBuilder();            java.Serialize(temp_list, temp_sb);

本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/sophiasy/archive/2010/11/12/6005557.aspx

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章