Ext.js项目(二)

人事管理模块:

     1.机构管理

     2.部门管理

     3.人员管理

一:用例图

 

二:数据表分析

三:需要涉及到的类:

需要涉及到的类:(完成一个模块时只需要修改包含:(----)即可)
ExtOA.Ent->BranchInfoBase
ExtOA.Ent->BranchInfo(----)
ExtOA.IDal->IBranchInfoDR(----)
ExtOA.SqlServerDal ->BranchInfoDRBase
ExtOA.SqlServerDal ->BranchInfoDR(-----)
ExtOA.Biz->BranchInfoBiz(-----)

四:在BranchInfoBiz中写两个重写的方法(Json格式):

引入的命名空间:


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

 /// <summary>
        /// 添加一条 BranchInfo   通过重写的方法
        /// </summary>
        /// <param name="ent">BranchInfo实体</param>
        /// <returns>1成功,-1失败,0异常 主键从实体里返回</returns>
        /// <exception cref="ex">异常信息</exception>
        /// <remarks>
        /// <para>Author: "fwy"</para>
        /// </remarks>
        public int AddBranchInfo(string entJson)
        {
            try
            {
                //自动转换成泛型对象
                BranchInfo branch = Newtonsoft.Json.JsonConvert.DeserializeObject<BranchInfo>(entJson);
                IBranchInfoDR dal = BranchInfoDal.Create(Config.Instance().Dal, Config.Instance().MyConnectstring);
                return dal.Add(branch);
            }
            catch (Exception ex)
            {
                ////log.Error("AddBranchInfo err:",ex);
                return 0;
            }
        }


   /// <summary>
        /// 更新一条 BranchInfo
        /// </summary>
        /// <param name="ent">BranchInfo实体</param>
        /// <returns>1成功,-1失败,0异常</returns>
        /// <exception cref="ex">异常信息</exception>
        /// <remarks>
        /// <para>Author: "fwy"</para>
        /// </remarks>
        public int SetBranchInfo(BranchInfo entJson)
        {
            try
            {
                BranchInfo branch = Newtonsoft.Json.JsonConvert.DeserializeObject<BranchInfo>(entJson);
                IBranchInfoDR dal = BranchInfoDal.Create(Config.Instance().Dal, Config.Instance().MyConnectstring);
                return dal.Set(branch);
            }
            catch (Exception ex)
            {
                ////log.Error("SetBranchInfo err:",ex);
                return 0;
            }
        }

 五:四种构造返回到前台数据的方法

 /// <summary>  四种构造返回到前台数据的方法
        /// 得到所有机构列表(Json格式)格式如下:
        /// {
        ///    total:5,
        ///    rows:[{},{},...]
        /// }
        /// </summary>
        /// <returns></returns>
        public string GetJsonBranchInfo()
        {
            JArray ja = new JArray();
            IList<BranchInfo> branchInfos = this.GetBranchInfo();
            //创建了一个json格式的对象
            foreach (BranchInfo branch in branchInfos)
            {
                JObject sj = new JObject();
                //与实体类中的一一对应
                JProperty Id = new JProperty("Id", branch.Id);
                sj.Add(Id);
                JProperty BranchName = new JProperty("BranchName", branch.BranchName);
                sj.Add(BranchName);
                JProperty BranchAddr = new JProperty("BranchAddr", branch.BranchAddr);
                sj.Add(BranchAddr);
                JProperty BranchPhone = new JProperty("BranchPhone", branch.BranchAddr);
                sj.Add(BranchPhone);
                JProperty BranchUrl = new JProperty("BranchUrl", branch.BranchAddr);
                sj.Add(BranchUrl);
                JProperty BranchMaster = new JProperty("BranchMaster", branch.BranchMaster);
                sj.Add(BranchMaster);

                UserInfo userinfo = (new UserInfoBiz()).GetUserInfoById(branch.BranchMaster);
                JProperty BranchMasterName = new JProperty("BranchMasterName", userinfo.UserName);
                sj.Add(BranchMasterName);
                //把对象添加到数组中去
                ja.Add(sj);
            }
            JObject j = new JObject();

            //给json对象中添加了一个属性
            JProperty total = new JProperty("total", branchInfos.Count);
            j.Add(total);
            JProperty rows = new JProperty("rows", ja);
            j.Add(rows);

            return j.ToString();
        }


        /// <summary>
        /// 得到所有机构列表(Json格式)格式如下:
        /// {
        ///    total:5,
        ///    rows:[{},{},...]
        /// }
        /// </summary>
        /// <returns></returns>
        public string GetJsonBranchInfo2()
        {
            JArray ja = new JArray();
            IList<BranchInfo> branchInfos = this.GetBranchInfo();
            foreach (BranchInfo branch in branchInfos)
            {
                JObject sj = new JObject();
                JProperty Id = new JProperty("Id", branch.Id);
                sj.Add(Id);
                JProperty BranchName = new JProperty("BranchName", branch.BranchName);
                sj.Add(BranchName);
                JProperty BranchAddr = new JProperty("BranchAddr", branch.BranchAddr);
                sj.Add(BranchAddr);
                JProperty BranchPhone = new JProperty("BranchPhone", branch.BranchAddr);
                sj.Add(BranchPhone);
                JProperty BranchUrl = new JProperty("BranchUrl", branch.BranchAddr);
                sj.Add(BranchUrl);
                UserInfo userinfo = (new UserInfoBiz()).GetUserInfoById(branch.BranchMaster);
                string BranchMasterJson = Newtonsoft.Json.JsonConvert.SerializeObject(userinfo);

                // JProperty BranchMaster = new JProperty("BranchMaster", BranchMasterJson);
                //把json对象还原成JObject
                JProperty BranchMaster = new JProperty("BranchMaster", JObject.Parse(BranchMasterJson));
                sj.Add(BranchMaster);

                ja.Add(sj);
            }

            JObject j = new JObject();
            JProperty total = new JProperty("total", branchInfos.Count);
            j.Add(total);
            JProperty rows = new JProperty("rows", ja);
            j.Add(rows);

            return j.ToString();

        }

        /// <summary>
        /// 得到所有机构列表(Json格式)格式如下:
        /// {
        ///    total:5,
        ///    rows:[{},{},...]
        /// }
        /// </summary>
        /// <returns></returns>
        public string GetJsonBranchInfo3()
        {
            JArray ja = new JArray();
            IList<BranchInfo> branchInfos = this.GetBranchInfo();
            foreach (BranchInfo branch in branchInfos)
            {
                JObject sj = new JObject();
                JProperty Id = new JProperty("Id", branch.Id);
                sj.Add(Id);
                JProperty BranchName = new JProperty("BranchName", branch.BranchName);
                sj.Add(BranchName);
                JProperty BranchAddr = new JProperty("BranchAddr", branch.BranchAddr);
                sj.Add(BranchAddr);
                JProperty BranchPhone = new JProperty("BranchPhone", branch.BranchPhone);
                sj.Add(BranchPhone);
                JProperty BranchUrl = new JProperty("BranchUrl", branch.BranchUrl);
                sj.Add(BranchUrl);

                UserInfo userinfo = (new UserInfoBiz()).GetUserInfoById(branch.BranchMaster);
                //去拼接所需要的格式
                string BranchMasterJson = "{" + string.Format("Id:{0},UserName:'{1}'", userinfo.Id, userinfo.UserName) + "}";
                JProperty BranchMaster = new JProperty("BranchMaster", JObject.Parse(BranchMasterJson));
                sj.Add(BranchMaster);

                ja.Add(sj);
            }

            JObject j = new JObject();
            JProperty total = new JProperty("total", branchInfos.Count);
            j.Add(total);
            JProperty rows = new JProperty("rows", ja);
            j.Add(rows);

            return j.ToString();

        }


        /// <summary>
        /// 得到所有机构列表(Json格式)格式如下:
        /// {
        ///    total:5,
        ///    rows:[{},{},...]
        /// }
        /// </summary>
        /// <returns></returns>
        public string GetJsonBranchInfo4()
        {
            JArray ja = new JArray();
            IList<BranchInfo> branchInfos = this.GetBranchInfo();
            foreach (BranchInfo branch in branchInfos)
            {
                var branchJson = Newtonsoft.Json.JsonConvert.SerializeObject(branch);
                JObject sj = JObject.Parse(branchJson);

                //外键的时候 先把外键删除  再重新构建
                sj.Remove("BranchMaster");
                UserInfo userinfo = (new UserInfoBiz()).GetUserInfoById(branch.BranchMaster);
                string BranchMasterJson = "{" + string.Format("Id:{0},UserName:'{1}'", userinfo.Id, userinfo.UserName) + "}";
                JProperty BranchMaster = new JProperty("BranchMaster", JObject.Parse(BranchMasterJson));
                sj.Add(BranchMaster);

                //UserInfo userinfo = (new UserInfoBiz()).GetUserInfoById(branch.BranchMaster);
                //JProperty BranchMasterName = new JProperty("BranchMasterName", userinfo.UserName);
                //sj.Add(BranchMasterName);



                ja.Add(sj);
            }

            JObject j = new JObject();
            JProperty total = new JProperty("total", branchInfos.Count);
            j.Add(total);
            JProperty rows = new JProperty("rows", ja);
            j.Add(rows);

            return j.ToString();

        }

 

 六:全局的Global.js中的代码
Ext.ns("Ext.OA");//基类的命名空间
Ext.ns("Ext.OA.HrManager"); //人事管理的命名空间
Ext.ns("Ext.OA.ScheduleManage"); //日常管理的命名空间
Ext.Msg.minWidth = 300;  // 设置Ext.Msg弹窗口的最小宽度
// 初始化错误提示
Ext.QuickTips.init();
// 统一指定错误信息提示方式
Ext.form.Field.prototype.msgTarget = 'side';

//隐藏提示进度条
function hideMessageBox() {
    setTimeout(function () { Ext.MessageBox.hide() }, 1000);
}

//显示提示进度条
function showMessageBox() {
    Ext.MessageBox.show
                            (
                                {
                                    msg: '数据加载中...',
                                    progressText: 'Loading...',
                                    width: 300,
                                    wait: true,
                                    waitConfig: { interval: 200 },
                                    icon: Ext.MessageBox.INFO
                                    //animEl: 'saving'
                                }
                            );
}

// 中文排序问题解决
// 重载 Ext.data.Store.prototype.applySort 函数以修复 DataStore 对汉字排序异常的问题
// var _applySort = Ext.data.Store.prototype.applySort;
// 如有需要,保存原 applySort 函数的引用

Ext.data.Store.prototype.applySort = function () { // 重载 applySort
    if (this.sortInfo && !this.remoteSort) { // sortInfo对象存在并且不是远程排序
        var s = this.sortInfo, f = s.field;
        var st = this.fields.get(f).sortType;
        var fn = function (r1, r2) {
            var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
            // 添加:修复汉字排序异常的Bug
            if (typeof (v1) == "string") { // 若为字符串类型,
                // 则用 localeCompare 比较汉字字符串, Firefox 与 IE 均支持
                return v1.localeCompare(v2);
            }
            // 若不是字符串类型
            return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
        };
        this.data.sort(s.direction, fn);
        if (this.snapshot && this.snapshot != this.data) { // 数据快照
            this.snapshot.sort(s.direction, fn);
        }
    }
};
NodeClick = function (node) {
   
    if (node.id == 93) { //考勤统计
        var userNode = { id: "93", text: "考勤统计" };
        KQTJ(userNode);
    } else if (node.id == 74) {
        //var userNode = { id: "74", text: "工单考核" };
        ZXKS();
    }
    else {
        Ext.Msg.alert("提示", "此操作还没有开发");
    }
}
// 关闭TabPanel标签
Ext.ux.TabCloseMenu = function () {
    var tabs, menu, ctxItem;
    this.init = function (tp) {
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }

    function onContextMenu(ts, item, e) {
        if (!menu) { // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: '关闭标签',
                iconCls: "closeone",
                handler: function () {
                    tabs.remove(ctxItem);
                }
            }, {
                id: tabs.id + '-close-others',
                text: '关闭其他标签',
                iconCls: "closeother",
                handler: function () {
                    tabs.items.each(function (item) {
                        if (item.closable && item != ctxItem) {
                            tabs.remove(item);
                        }
                    });
                }
            }, {
                id: tabs.id + '-close-all',
                text: '关闭全部标签',
                iconCls: "closeall",
                handler: function () {
                    tabs.items.each(function (item) {
                        if (item.closable) {
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function () {
            if (this != item && this.closable) {
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        var disableAll = true;
        tabs.items.each(function () {
            if (this.closable) {
                disableAll = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-all').setDisabled(disableAll);
        menu.showAt(e.getPoint());
    }
};

// 内容为grid
GridAdd = function (node, grid) {
    var tab = center.add({
        id: node.id,
        iconCls: "tabicon",
        xtype: "panel",
        title: node.text,
        closable: true,
        layout: "fit",
        frame: true,
        items: [grid]
    });
    center.setActiveTab(tab);
    grid.show();
}
// 写cookies函数
function setCookie(name, value)// 两个参数,一个是cookie的名子,一个是值
{
    var Days = 30; // 此 cookie 将被保存 30 天
    var exp = new Date(); // new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires="
			+ exp.toGMTString();
}
// 取cookies函数
function getCookie(name) {
    var arr = document.cookie
			.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null)
        return unescape(arr[2]);
    return null;

}
// 删除cookie
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

 七:DeskTop调用机构管理Window
     1.编写机构管理窗体JS类

Ext.OA.HrManager.BranchInfoWin = function() {
    this.main = new Ext.Window({
        id: "rsgl_jggl_win",
        title: "机构管理",
        width: 600,
        iconCls: 'jggl',
        height: 400,
        closeAction: 'hide',
        plain: true,
        modal: true,
        draggable: true,
        closable: true,
        layout: "fit"
    });
}

2.在desktop.js中编写调用代码:

…
items: [{
					text: '机构管理',
					iconCls: 'jggl',
					handler: this.createWindow,
//为了obj.windowId 必须 scope: this, scope: this, windowId: 'rsgl_jggl' } …

 注意:

createWindow: function(obj) {
			var desktop = this.app.getDesktop();
			var win = desktop.getWindow(obj.windowId);
			var winObj = null;
			if (!win) {
				if (obj.windowId == "rsgl_jggl")
					winObj =Ext.OA.HrManager.BranchInfoWin;

				win = desktop.createWindow(winObj);
			}

			win.show();
		}

 

八:机构管理前后台数据的交互:

    1.编写后台管理数据的页面:GetBranchInfo.aspx

 

  protected void Page_Load(object sender, EventArgs e)
    {
//判断是添加还是修改 if (Request["act"].ToString() == "create") { string branchInfoJson = Request["name"].ToString(); BranchInfoBiz helper = new BranchInfoBiz(); int result = helper.AddBranchInfo(branchInfoJson); if (result > 0) { Response.Write("{success:true,result:" + result + ",message:'添加机构信息成功'}"); } else { Response.Write("{success:false,result:0,message:'添加机构信息失败!'}"); } } else if (Request["act"].ToString() == "update") { string branchInfoJson = Request["name"].ToString(); BranchInfoBiz helper = new BranchInfoBiz(); int result = helper.SetBranchInfo(branchInfoJson); if (result > 0) { Response.Write("{" + string.Format("success:true,result:{0}", result) + ",message:'修改机构信息成功!'}"); } else { Response.Write("{success:false,result:0,message:'修改机构信息失败!'}"); } } else if (Request["act"].ToString() == "delete") { int id = int.Parse(Request["name"].ToString()); BranchInfoBiz helper = new BranchInfoBiz(); int result = helper.DelBranchInfo(id); if (result>0) Response.Write("{" + string.Format("success:true,result:{0}", result) + ",message:'删除机构信息成功!'}"); else Response.Write("{success:false,result:0,message:'删除机构信息失败!'}"); } else { BranchInfoBiz helper = new BranchInfoBiz(); string json = helper.GetJsonBranchInfo3(); //string json = helper.GetJsonBranchInfo(); Response.Write(json); } }

 2.编写BranchInfoMgr.js(注意Grid配置项):

Ext.OA.HrManager.BranchInfoWin = function() {

	var url = "/Web/Manage/DeskTop/JSON/GetBranchInfo.aspx";

    //通过扩展方法创建Grid
	Ext.ux.BranchInfoGrid = Ext.extend(Ext.ux.EasyGrid, {
        //调用父类的构造函数
		initComponent: function() {
			Ext.ux.BranchInfoGrid.superclass.initComponent.call(this);
		}
	});
        //下拉列表分页返回的数据
	var LeaderStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
//-1为无条件的 url: "/Web/Manage/DeskTop/JSON/GetSimpleUserInfo.aspx?condition=-1" }), reader: new Ext.data.JsonReader( { totalProperty: 'totalProperty', root: 'root' }, [{ name: "LeaderId", type: "int" }, { name: "LeaderName", type: "string"}] ) }); LeaderStore.load(); var cbxLeader = new Ext.form.ComboBox({ fieldLabel: "负责人", labelStyle: "width:130px", width: 125, editable: false, id: "cbxLeader", name: "cbxLeader", pageSize: 5, store: LeaderStore, emptyText: "--请选择--", mode: "remote", displayField: "LeaderName", valueField: "LeaderId", hiddenName: "BranchMaster", triggerAction: "all", selectOnFocus: true, listWidth: 200 }); //获取外键的值 var renderBranchMaster = function(value) { if (value) { return value.UserName; } }; //与扩展的Grid参数一致 var fnCreate = function(_store, _form, _record) { _record.data.Id = 0; var params = Ext.encode(_record.data); Ext.Ajax.request({ url: url, success: function(response) { //alert(response.responseText); var json = Ext.decode(response.responseText); if (json.success) { var _combo = _form.findField("cbxLeader"); var branchId = _combo.getValue(); var branchName = _combo.getRawValue(); //得到comboBox选中的Text _record.set("BranchMaster", { "Id": branchId, "UserName": branchName }); _record.set("Id", json.result); _record.commit(); _store.add(_record); //_store.reload(); } else { Ext.Msg.alert("OA智能办公平台", json.message); } }, faiure: function(response) { Ext.Msg.alert("OA智能办公平台", "添加机构失败!"); }, params: { act: "create", name: params, temp: (new Date()).getTime() } }); }; var fnUpdate = function(_form, r) { var params = Ext.encode(_form.getFieldValues()); Ext.Ajax.request({ url: url, success: function(response) { var json = Ext.decode(response.responseText); if (json.success) { var values = _form.getFieldValues(); r.beginEdit(); for (var name in values) { r.set(name, values[name]); } var _combo = _form.findField("cbxLeader"); var branchId = _combo.getValue(); var branchName = _combo.getRawValue(); //得到comboBox选中的Text r.set("BranchMaster", { "Id": branchId, "UserName": branchName }); r.set("Id", json.result); r.endEdit(); r.commit(); //_store.reload(); } else { Ext.Msg.alert("OA智能办公平台", json.message); } }, faiure: function(response) { Ext.Msg.alert("OA智能办公平台", "修改机构失败!"); }, params: { act: "update", name: params, temp: (new Date()).getTime() } }); }; var fnDelete = function(_store, r) { var params = r.data.Id; Ext.Ajax.request({ url: url, success: function(response) {
//查看返回内容的写法 //alert(response.responseText);
//把字符串变成对象 提示弹出 var json = Ext.decode(response.responseText);
if (json.success) {
//删除成功 直接移除store 对象 _store.remove(r); //_store.reload(); } else { Ext.Msg.alert("OA智能办公平台", json.message); } }, faiure: function(response) { Ext.Msg.alert("OA智能办公平台", "删除失败!"); },
//清掉缓存的参数 params: { act: "delete", name: params, temp: (new Date()).getTime() } }); }; var fnWinModify = function(_form, _record) { var _combo = _form.findField("cbxLeader"); _combo.setValue(_record.data.BranchMaster.Id); _combo.setRawValue(_record.data.BranchMaster.UserName); }; //直接继承下来的Grid var branchInfoGrid = new Ext.ux.BranchInfoGrid({ title: "机构管理", //width: 400, autoWidth:true, url: url + "?act=read", type: "json", header: false, //去掉头部的标签 headerAsText: false, height: 400, fnCreate: fnCreate, fnUpdate: fnUpdate, fnDelete: fnDelete, //修改显示的时候并不是全是文本框 fnWinModify: fnWinModify, subFormConfig: { create: { width: 400, height: 300, title: "添加机构", items: { ids: [5], fields: [cbxLeader] } },
update: { width: 400, height: 300, title: "修改机构" } }, //跟实体类的属性一致 fields: ['Id', 'BranchName', 'BranchAddr', 'BranchPhone', 'BranchUrl', 'BranchMaster'], headers: ['ID', '机构名称', '住址', '联系电话', '网址', '负责人'], // 第一种方式的写法 //fields: ['Id', 'BranchName', 'BranchAddr', 'BranchPhone', 'BranchUrl', 'BranchMaster',"BranchMasterName"], //headers: ['ID', '机构名称', '住址', '联系电话', '网址', '负责人ID',"负责人"], //隐藏列 colhidden: [0], //colhidden: [0,5], //显示的外键 renderer: { ids: [5], funcs: [renderBranchMaster] } }); var labelTitle = new Ext.form.Label({ height: 20, html: "<img src='/Web/images/right_arrow.gif' alt='' align='absmiddle'/> 当前位置: 人事管理 > 机构管理" }); this.main = new Ext.Window({ id: "rsgl_jggl_win", title: "机构管理", width: 600, iconCls: 'jggl', height: 400, closeAction: 'hide', plain: true, modal: true, draggable: true, closable: true, //layout: "fit", items: [labelTitle, branchInfoGrid] }); }

 

 3.下拉列表的加载:

      1.首先创建一个视图(减少对数据的查询    只返回姓名和职位即可):

      

SELECT   a.Id, a.UserName, b.DutyDesc
FROM      dbo.UserInfo AS a INNER JOIN
                dbo.DutyInfo AS b ON a.DutyInfoNo = b.Id

   2.IDal层的代码:

     /// <summary>
        /// 分页获取用户数据(返回用户ID和用户名)
        /// </summary>
        /// <param name="startIndex">起始条数(从第0条开始)</param>
        /// <param name="pagesize">每页几条记录</param>
        /// <param name="condition">条件:默认为'1=1'</param>
        /// <param name="key">主键名称,默认为'id'</param>
        /// <param name="totalcount">分页前的总数</param>
        /// <returns></returns>
        DataTable GetSimpleUserInfoByPager(int startIndex, int pagesize, string condition, string key, out int totalcount);

 

  3.Dal层的代码:

 /// <summary>
        /// 获取简单用户数据(仅返回ID,UserName)
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="pagesize"></param>
        /// <param name="condition"></param>
        /// <param name="key"></param>
        /// <param name="totalcount"></param>
        /// <returns></returns>
        public DataTable GetSimpleUserInfoByPager(int startIndex, int pagesize, string condition, string key, out int totalcount)
        {

            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionString))
            {
                
                string strsql = string.Format("exec GetDataByPager {0},'{1}',{2},'{3}','{4}'", 
startIndex, "v_SimpleUserInfo", pagesize, condition, key); connection.Open(); SqlDataAdapter da = new SqlDataAdapter(strsql, connection); DataSet ds = new DataSet(); try { da.Fill(ds); totalcount = int.Parse(ds.Tables[1].Rows[0][0].ToString()); return ds.Tables[0]; } catch { totalcount = 0; return null; } } }

 

4.BLL层的代码:
 public DataTable GetSimpleUserInfoByPager(int startIndex, int pagesize, out int totalcount, string condition)
        {
            try
            {
                IUserInfoDR dal = UserInfoDal.Create(Config.Instance().Dal, Config.Instance().MyConnectstring);
                return dal.GetSimpleUserInfoByPager(startIndex, pagesize, condition, "id", out totalcount);

            }
            catch (Exception ex)
            {
                //log.Error("GetUserInfoById err:",ex);
                totalcount = 0;
                return null;
            }
        }

 5.页面后台调用代码:

public partial class Manage_desktop_JSON_GetSimpleUserInfo : System.Web.UI.Page
{
    /// <summary>
    /// 起始条数(从0开始)
    /// </summary>
    public int StartIndex
    {
        get
        {
            if (Request["start"] != null)
            {
                return int.Parse(Request["start"].ToString());
            }
            else
            {
                return 0;
            }
        }
    }
    /// <summary>
    /// 分页的条数,默认为5
    /// </summary>
    public int PageSize
    {
        get
        {
            if (Request["limit"] != null)
            {
                return int.Parse(Request["limit"].ToString());
            }
            else
            {
                return 5;
            }
        }
    }

     /// <summary>
     /// 最终返回的数据
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        string outputString = this.JsonHeader() + this.JsonBody() + this.JsonFooter();
        Response.Write(outputString);
        Response.End();
    }

    private string JsonFooter()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("],'totalProperty':" + this.TotalRecord.ToString() + "}");
        return sb.ToString();
    }

   /// <summary>
   /// 查询条件  -1为无条件
   /// </summary>
    private string Condition
    {
        get
        {
            if (Request["condition"] != null)
                return Request["condition"].ToString();
            else
                return "";
        }
    }
    /// <summary>
    /// 循环输出Json字符串
    /// </summary>
    /// <returns></returns>
    private string JsonBody()
    {
        StringBuilder sb = new StringBuilder();
        int totalcount = 0;
        UserInfoBiz helper = new UserInfoBiz();

        DataTable  userinfos = null;
       
        if (this.Condition == "-1")
            userinfos = helper.GetSimpleUserInfoByPager(this.StartIndex,this.PageSize,out totalcount);
              
        else
        {
            string condition = string.Format("dutydesc like ''{0}%''", this.Condition); //edit by fwy
            userinfos = helper.GetSimpleUserInfoByPager(this.StartIndex, this.PageSize, out totalcount, condition);
               
        }

        this.TotalRecord = totalcount;
      
        int count = 0;
        foreach (DataRow row in userinfos.Rows)
        {
            count++;
            sb.Append("{");
            sb.AppendFormat("'LeaderId':'{0}','LeaderName':'{1}'", row["Id"].ToString(), row["UserName"].ToString());
            sb.Append("}");
            if (count != userinfos.Rows.Count) sb.Append(",");
        }
        //sb.Append("{}")
        return sb.ToString();
    }

    private string JsonHeader()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("{'root':[");
        return sb.ToString();

    }


    public int TotalRecord
    {
        get
        {
            if (ViewState["TotalRecord"] != null)
                return (int)ViewState["TotalRecord"];
            else
                return 0;
        }
        set
        {
            ViewState["TotalRecord"] = value;
        }
    }
}

 构造后的数据:

前台传递过来的url类似于:
http://localhost:15742/Web/Manage/DeskTop/JSON/GetSimpleUserInfo.aspx?start=0&limit=5&condition=-1
后台返回的数据的格式:
{'root':[{'LeaderId':'1','LeaderName':'王志'},{'LeaderId':'2','LeaderName':'Admin'},{'LeaderId':'4','LeaderName':'钱玉'},{'LeaderId':'3','LeaderName':'张阳'},{'LeaderId':'5','LeaderName':'梅燕'}],'totalProperty':27}

 这篇写的已经很多了,前台Ext.jsde 代码下篇在写吧。

 



posted @ 2016-08-28 20:23  石shi  阅读(800)  评论(0编辑  收藏  举报