asp.net下利用MVC模式实现Extjs表格增删改查

在网上看到有很多人写extjs下的表格控件的增删改查,但是大多数都是直接从后台读取数据,很少有跟数据库进行交互的模式。

今天就来写一个这样的例子。欢迎大家交流指正。

 

首先简单介绍一下MVC模式,MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写。

Model(模型)
是应用程序中用于处理应用程序数据逻辑的部分。
通常模型对象负责在数据库中存取数据。
View(视图)
是应用程序中处理数据显示的部分。
通常视图是依据模型数据创建的。
Controller(控制器)
是应用程序中处理用户交互的部分。
通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
 
下面就为大家说明代码示例:
 
视图部分:
前台JS部分代码:
Ext.onReady(function () {
                    var csm = new Ext.grid.CheckboxSelectionModel({//创建checkbox对象
                        handleMouseDown: new Ext.emptyFn()
                    });
                    var cum = new Ext.grid.ColumnModel([
                    csm, //checkbox对象
                    {header: "用户ID", dataIndex: "id", sortable: true
                  },
                    { header: ‘用户姓名‘, dataIndex: ‘name‘, sortable: true,
                        editor: new Ext.grid.GridEditor(
                        new Ext.form.TextField({ allowBlank: false }))
                    },
                    { header: ‘性别‘, dataIndex: ‘sex‘, sortable: true,
                        editor: new Ext.grid.GridEditor(
                        new Ext.form.TextField({ allowBlank: false }))
                    }
                   ]);
                ;

                var store = new Ext.data.Store({
                    proxy: new Ext.data.HttpProxy({ url: ‘UserData.aspx‘ }),
                    reader: new Ext.data.JsonReader({
                        totalProperty: ‘totalCount‘, //json字符串中的字段,数据量大小
                        root: ‘data‘//json字符串中的字段
                    }, [
                            { name: ‘id‘ },
                            { name: ‘name‘ },
                            { name: ‘sex‘ }
                        ]),
                    remoteSort: true
                });
                var Record = Ext.data.Record.create([
                           { name: ‘id‘, type: ‘string‘ },
                        { name: ‘name‘, type: ‘string‘ },
                        { name: ‘sex‘, type: ‘string‘ }
                        ]);
                store.load({ params: { start: 0, limit: 5} }); //运行加载表格数据

                var cumgrid = new Ext.grid.EditorGridPanel({
                    renderTo: ‘cumGrid‘,
                    store: store,
                    stripeRows: true, //斑马线效果
                    viewConfig: {
                        forceFit: true,
                        columnsText: "显示的列",
                        sortAscText: "升序",
                        sortDescText: "降序"
                    },
                    height: 200,
                    width: 550,
                    sm: csm,
                    bbar: new Ext.PagingToolbar({
                        pageSize: 5, //每页信息条数
                        store: store,
                        autowidth: true,
                        autoHeight: true,
                        displayInfo: true,
                        prevText: "上一页",
                        nextText: "下一页",
                        refreshText: "刷新",
                        lastText: "最后页",
                        firstText: "第一页",
                        beforePageText: "当前页",
                        afterPageText: "共{0}页",
                        displayMsg: ‘显示第{0}条到第{1}条记录,一共{2}条‘,
                        emptyMsg: ‘没有记录‘
                    }),
                    tbar: new Ext.Toolbar([‘-‘, {
                        text: ‘添加一行‘,
                        handler: function () {
                            var win = new Ext.Window({
                                title: ‘添加用户‘,
                                layout: ‘fit‘,   
                                height: 300,   
                                width: 300, 
                                border: 0,    
                                frame: true,    //去除窗体的panel框架
                                plain: true,
                                html: ‘<iframe frameborder=0 width="100%" height="100%" allowtransparency="true" scrolling=auto src="addUser.htm"></iframe>‘
                            });
                            win.show();    //显示窗口

                        }
                    }, ‘-‘, {
                        text: ‘删除一行‘,
                        handler: function () {
                            Ext.Msg.confirm(‘信息‘, ‘确定要删除?‘, function (btn) {
                                if (btn = ‘yes‘) {
                                    var id = "";
                                    function getid() {
                                        for (var i = 0; i < cumgrid.getSelectionModel().getSelections().length; i++) {
                                            id += cumgrid.getSelectionModel().getSelections()[i].get("id");
                                            id += ‘,‘;
                                        }
                                    };
                                    getid(); //初始化选中行id字符串数组
                                    Ext.Ajax.request({
                                        url: "DelUserInfo.aspx",
                                        method: "post",
                                        params: { id: id },
                                        success: function (response) {
                                            Ext.Msg.alert("恭喜", "删除成功了!");
                                            store.reload();
                                        },
                                        failure: function () {
                                            Ext.Msg.alert("提 示", "删除失败了!");
                                        }
                                    })
                                }
                            });
                        }
                    }, ‘-‘, {
                        text: ‘保存‘,
                        handler: function () {
                            var m = store.getModifiedRecords().slice(0);
                            var jsonArray = [];
                            Ext.each(m, function (item) {
                                jsonArray.push(item.data);

                            })

                            if (false) {//判断条件
                                return;
                            } else {

                                // alert(Ext.encode(jsonArray))

                                Ext.Ajax.request({
                                    //url: "Demo/Operator.aspx",
                                    url: "SaveUserInfo.aspx",
                                    method: "POST",
                                    params: ‘data=‘ + encodeURIComponent(Ext.encode(jsonArray)),
                                    success: function (response, option) {
                                        store.reload();
                                        alert(response.responseText);
                                    },
                                    failure: function (response) {
                                        store.reload();
                                        alert(response.responseText)
                                        Ext.Msg.alert("提示", "修改失败了!");
                                    }
                                });
                            }
                        }
                    }, ‘-‘]),
                    cm: cum
                });
                cumgrid.render(); //刷新表格
            });

技术分享

 

表格界面如上图所示。增删改查分别通过,添加,删除,保存修改,和后台读取数据并分页实现。

 
业务处理部分:
UserBll.cs:
public class UserBLL
{
    public UserBLL()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    UserDao dao = new UserDao();
    JsonHelper json = new JsonHelper();
    DataTable dt = new DataTable();
    //获取全部数据
    public string GetUserInfo() 
    {
        dt = dao.GetAllInfo();//从数据库中读取数据
        json.success = true;
        foreach (DataRow dr in dt.Rows) //将读取出的数据转换成字符串
        {
            json.AddItem("id", dr["id"].ToString());
            json.AddItem("name", dr["name"].ToString());
            json.AddItem("sex", dr["sex"].ToString());
            json.ItemOk();
        }
        string jsons = json.ToString();
        return jsons;
    }
    //根据id获取用户数据
    public UserBean getUserInfosNoState(int id) 
    {
        return dao.getUserInfosNoState(id);
    }
    //分页获取数据
    public string GetUserInfoPage(int start, int limit)
    {
        JSONHelper json = new JSONHelper();
        dt = dao.GetUserInfoPaging(start, limit); //从数据库中读取数据
        json.success = true;
        foreach (DataRow dr in dt.Rows) //将读取出的数据转换成字符串
        {
            json.AddItem("id", dr["id"].ToString());
            json.AddItem("name", dr["name"].ToString());
            json.AddItem("sex", dr["sex"].ToString());
            json.ItemOk();
        }
        json.totlalCount = dao.GetAllUserCount();
        string jsons = "";
        if (json.totlalCount > 0)
        {
            jsons = json.ToString();
        }
        else
        {
            jsons = @"{success:false}";
        }
        return jsons;
    }
    //删除用户信息
    public int DelUserInfos(int id)
    {
        return dao.DelUserInfos(id);
    }
    //更新用户信息
    public int SaveUserInfo(UserBean user)
    {
        return dao.SaveUserInfo(user);
    }
    //添加用户信息
    public int AddUserInfo(UserBean user)
    {
        return dao.AddUserInfo(user);
    }


}

 

后台查询数据部分:
UserData.aspx.cs:
     public string ds = string.Empty;
        public UserBLL ub = new UserBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            string starts = Request.Form["start"];//获取读取数据的范围
            string limits = Request.Form["limit"];
            int index = Convert.ToInt32(starts);
            int length = Convert.ToInt32(limits);
            ds = ub.GetUserInfoPage(index, length);
        }

 

增加数据:

AddUserInfo.aspx.cs:

UserBLL ub = new UserBLL();
    protected void Page_Load(object sender, EventArgs e)
    {
        AddUserInfos();
    }

    public void AddUserInfos() //添加数据
    {
        //获取姓名性别
        string name = Request.Form["name"];
        string sex = Request.Form["sex"];
        UserBean user = new UserBean();
        user.Name = name;
        user.Sex = sex;
        int count = ub.AddUserInfo(user);
        if (count > 0)
            Response.Write(@"{success:true}");
        else
            Response.Write(@"{success:false}");
    }

 

删除数据部分:

DelUserInfo.aspx.cs:

需要注意因为从前台传来的是所有改变行所有数据id的json字符串,需要进行字符串分割获取到要删除行的id

UserBLL ub = new UserBLL();  
    protected void Page_Load(object sender, EventArgs e)
    {
        DeleteRoomInfo();
    }
    public void DeleteRoomInfo()
    {
        string id = Request.Form["id"];//获取要删除用户的id字符串
        if (id != null)
        {
            string[] ids = id.Split(,);//将每一名用户的id分割存入字符串数组
            try
            {
                foreach (string r in ids)
                {
                    ub.DelUserInfos(Convert.ToInt32(r));//循环删除用户信息
                }
                Response.Write(@"{success:true}");
            }
            catch (Exception)
            {
                Response.Write(@"{success:false}");
            }

        }
        else
        {
            Response.Write(@"{success:false}");
        }
    }

 

修改数据部分:

SaveUserInfo.aspx.cs:

此处需要注意,因为前台传来的是所有改变行所有数据的json字符串,需要进行分割处理,先去掉多余的字符,在根据‘,‘分割成“数据名:数据值的形式”,再循环根据:进行分割

UserBLL ub = new UserBLL();
    protected void Page_Load(object sender, EventArgs e)
    {
        SaveRoomInfo();
    }
    public void SaveRoomInfo()
    {
        int count=0;
        string data = Request.Form["data"];// 对传值过来的json字符串进行处理,分解成键值对

        data = RemoveChars(data,"[");
        data = RemoveChars(data, "]");
        data = RemoveChars(data,"\"");
        data = RemoveChars(data, "}");
        data = RemoveChars(data, "{");
        string[] field = data.Split(,);
        string[] keyvalue;
        for (int i = 0; i < field.Length / 3; i++)
        {
            UserBean user = new UserBean();
            for (int j = i * 3, k = 0; k < 3; j++, k++)
            {
                keyvalue = field[j].Split(:);//将json字符串中的数据项名和数据项值分开,分别存入user对象中
                if (keyvalue[0] == "id")
                {
                    user.Id = Convert.ToInt32(keyvalue[1]);
                }
                else if (keyvalue[0] == "name")
                {
                    user.Name = keyvalue[1];
                }
                else if (keyvalue[0] == "sex")
                {
                    user.Sex = keyvalue[1];
                }
            }
            count = ub.SaveUserInfo(user);
        }
        if (count > 0)
        {
            Response.Write("{success:‘true‘},{data:" + field[2] + "}");
        }
        else
        {
            Response.Write("{success:‘false‘},{data:" + field[2] + "}");
        }
            
    }

    //删除字符串中某个字符
    static string RemoveChars(string str, string remove)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(remove))
        {
            throw new ArgumentException("....");
        }

        StringBuilder result = new StringBuilder(str.Length);

        Dictionary<char, bool> dictionary = new Dictionary<char, bool>();

        foreach (char ch in remove)
        {
            dictionary[ch] = true;
        }

        foreach (char ch in str)
        {
            if (!dictionary.ContainsKey(ch))
            {
                result.Append(ch);
            }
        }

        return result.ToString();
    }

 

 

 

模型部分:

UserBean.cs:

public class UserDao
{
    public UserDao()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    private DataTable dt;
    public DataTable GetAllInfo() 
    {
        try 
        {
            return SqlHelper.ExecuteDataTable("select * from T_user");
        }
        catch(Exception){throw;}
    }
    //分页读取数据
    public DataTable GetUserInfoPaging(int start, int limit) 
    {
        try
        {
            return SqlHelper.ExecuteDataTable("select top " + limit + " * from T_user where id not in(select top " + start + " id from T_user order by id asc) order by id asc");
        }
        catch (Exception) { throw; }
    }

    public UserBean getUserInfosNoState(int id) 
    {
        try
        {
            dt = SqlHelper.ExecuteDataTable("select * from T_user where id=" + id);
            UserBean user = new UserBean();
            user.Id = int.Parse(dt.Rows[0]["id"].ToString());
            user.Name = dt.Rows[0]["name"].ToString();
            user.Sex = dt.Rows[0]["sex"].ToString();
            return user;
        }
        catch (Exception){ throw; }
    }

    //获得用户总数
    public int GetAllUserCount() 
    {
        try
        {
            return (int)SqlHelper.ExecuteScalar("select count(*) from T_user");
        }
        catch (Exception) { throw; }
    }

    //删除用户信息
    public int DelUserInfos(int id)
    {
        try
        {
            int count = SqlHelper.ExecuteNonQuery("delete T_user where id=" + id);
            return count;
        }
        catch (Exception){ throw; }
    }

    //保存修改
    public int SaveUserInfo(UserBean user)
    {
        try
        {
            int count = SqlHelper.ExecuteNonQuery("update T_user set name=‘" + user.Name + "‘,sex=‘" + user.Sex + "‘ where id=" + user.Id);
            return count;
        }
        catch (Exception){ throw;}
    }

    //新增用户
    public int AddUserInfo(UserBean user)
    {
        try
        {
            int count = SqlHelper.ExecuteNonQuery("insert into T_user values(‘" + user.Name + "‘,‘" + user.Sex + "‘)");
            return count;
        }
        catch (Exception)
        { throw; }
    }
}

 

UserBean.cs

public class UserBean
{
    public UserBean()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    private long id;
    private string sex;
    private string name;

    public long Id
    {
        get { return id; }
        set { id = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string Sex
    {
        get { return sex; }
        set { sex = value; }
    }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。