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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值