所謂磨刀不誤砍柴工,先寫點通用的代碼,後面開發起來效率就高多了。多餘的話就不敲了,先簡單介紹介紹吧。
時間格式化
對於序列化JSON,我喜歡用JSON.NET,爲了方便,我定義了一個擴展方法,如下面代碼:
1: /// <summary>
2: /// 將對象序列化爲JSON數據
3: /// </summary>
4: /// <param name="instance"></param>
5: /// <returns></returns>
6: public static string ToJson(this object instance)
7: {
8: return JsonConvert.SerializeObject(instance);
9: }
那麼序列化JOSN輸出那麼就方便多了,如下面代碼:
1: var info = from a in db.TB_KTVAndConcert
2: join b in db.TB_City on a.Cityid equals b.ID
3: where a.AttributeCode == "AttrubuteCode".GetRequest()
4: orderby a.Cityid
5: select new
6: {
7: a.CreateDate,
8: a.Defaultflag,
9: a.ID,
10: a.Name,
11: a.Cityid,
12: b.CityName,
13: a.Displayindex
14: };
15: if ("CityID".GetRequest().IsNotEmpty())
16: {
17: if (MyRegex.IsNumberRegex("CityID".GetRequest()))
18: {
19: int cityId = Convert.ToInt32("CityID".GetRequest());
20: info = info.Where(p => p.Cityid == cityId);
21: }
22: }
23: context.Response.Write(info.OrderByDescending(p => p.Defaultflag).ThenBy(p => p.Displayindex).ToJson());
序列化JSON是可以了,但是前臺顯示DateTime類型數據時顯示就有問題了,也就是獲取不到想要的格式化字符串。解決這個問題有兩種方式,方式一就是定義一個C#方法來返回格式化時間字符串,關鍵部分代碼如下:
1: select new
2: {
3: CreateDate = a.CreateDate.GetDateTimeString(),
4: a.Defaultflag,
5: a.ID,
6: a.Name,
7: a.Cityid,
8: b.CityName,
9: a.Displayindex
10: };
這樣雖然可以,但是如果我想統一在瀏覽器端處理呢?於是封裝下面的函數:
1: //時間格式化
2: Date.prototype.format = function (format) {
3: if (!format) {
4: format = "yyyy-MM-dd hh:mm:ss";
5: }
6: var o = {
7: "M+": this.getMonth() + 1, // month
8: "d+": this.getDate(), // day
9: "h+": this.getHours(), // hour
10: "m+": this.getMinutes(), // minute
11: "s+": this.getSeconds(), // second
12: "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
13: "S": this.getMilliseconds()
14: // millisecond
15: };
16: if (/(y+)/.test(format)) {
17: format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
18: }
19: for (var k in o) {
20: if (new RegExp("(" + k + ")").test(format)) {
21: format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
22: }
23: }
24: return format;
25: };
26: function fomatDate(str) {
27: return (new Date(parseInt(str.substring(str.indexOf('(') + 1, str.indexOf(')'))))).format("yyyy-MM-dd hh:mm:ss");
28: }
前臺調用:
1: function formatCreateDate(value, row, index) {
2:
3: return fomatDate(row.CreateDate);
4:
5: }
顯示效果:
消息框
彈出框以及系統消息框
1: function showMsg(title, msg, isAlert) {
2: if (isAlert !== undefined && isAlert) {
3: $.messager.alert(title, msg);
4: } else {
5: $.messager.show({
6: title: title,
7: msg: msg,
8: showType: 'show'
9: });
10: }
11: }
確認框
1: function showConfirm(title, msg, callback) {
2: $.messager.confirm(title, msg, function (r) {
3: if (r) {
4: if (jQuery.isFunction(callback))
5: callback.call();
6: }
7: });
8: }
進度框
1: function showProcess(isShow, title, msg) {
2: if (!isShow) {
3: $.messager.progress('close');
4: return;
5: }
6: var win = $.messager.progress({
7: title: title,
8: msg: msg
9: });
10: }
例如在表單提交時,爲了防止重複提交,會顯示一個進度框。提交完成時,關閉進度框並提示操作信息:
1: function submitForm(url) {
2: $('#ff').form('submit', {
3: url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
4: onSubmit: function () {
5: var flag = $(this).form('validate');
6: if (flag) {
7: showProcess(true, '溫馨提示', '正在提交數據...');
8: }
9: return flag
10: },
11: success: function (data) {
12: showProcess(false);
13: if (data == 1) {
14: top.showMsg('溫馨提示', '提交成功!');
15: if (parent !== undefined) {
16: if ($.isFunction(window.reloadParent)) {
17: reloadParent.call();
18: } else {
19: parent.$("#tt").datagrid('reload');
20: parent.closeMyWindow();
21: }
22: }
23: } else {
24: $.messager.alert('溫馨提示', data);
25: }
26: },
27: onLoadError: function () {
28: showProcess(false);
29: $.messager.alert('溫馨提示', '由於網絡或服務器太忙,提交失敗,請重試!');
30: }
31: });
32: }
關鍵頁面代碼如下:
1: <div class="easyui-layout" style="text-align: left; height: 270px;" fit="true">
2:
3: <div region="center" border="false" style="padding: 10px; background: #fff; border: 1px solid #ccc;">
4:
5: <form id="ff" method="post">
6:
7: <input type="hidden" name="id" value="" />
8:
9: <table border="0" cellpadding="0" cellspacing="0">
10:
11: <tr>
12:
13: <td>
14:
15: <label for="AdminLogin">
16:
17: 登錄名:</label>
18:
19: </td>
20:
21: <td>
22:
23: <input class="easyui-validatebox" style="width: 300px;" type="text" required="true"
24:
25: validtype="length[0,20]" name="AdminLogin"></input>
26:
27: </td>
28:
29: </tr>
30:
31: <tr>
32:
33: <td>
34:
35: <label for="RoleID">
36:
37: 所屬角色:</label>
38:
39: </td>
40:
41: <td>
42:
43: <input class="easyui-combobox" valuefield="ID" textfield="RoleName" panelheight="auto"
44:
45: editable="false" style="width: 300px;" url="/Ajax/Common.ashx?Type=GetRoles"
46:
47: required="true" name="RoleID"></input>
48:
49: </td>
50:
51: </tr>
52:
53: <tr>
54:
55: <td colspan="2" style='color: Red'>
56:
57: 在編輯時,輸入管理員密碼錶示重新設置密碼。
58:
59: </td>
60:
61: </tr>
62:
63: <tr>
64:
65: <td>
66:
67: <label for="AdminPassword">
68:
69: 密碼:</label>
70:
71: </td>
72:
73: <td>
74:
75: <input class="easyui-validatebox" style="width: 300px;" type="text" validtype="length[6,20]"
76:
77: id='txtPassword' name="AdminPassword"></input>
78:
79: </td>
80:
81: </tr>
82:
83: <tr>
84:
85: <td>
86:
87: <label for="AdminPassword2">
88:
89: 確認密碼:</label>
90:
91: </td>
92:
93: <td>
94:
95: <input class="easyui-validatebox" style="width: 300px;" type="text" validtype="length[6,20]"
96:
97: id='txtPassword2' name="AdminPassword2"></input>
98:
99: </td>
100:
101: </tr>
102:
103: <tr>
104:
105: <td>
106:
107: <label for="Defatulflag">
108:
109: 是否上架:</label>
110:
111: </td>
112:
113: <td>
114:
115: <input type="checkbox" name="Defatulflag" class="easyui-validatebox" type="text"
116:
117: required="true" value="1" />
118:
119: </td>
120:
121: </tr>
122:
123: </table>
124:
125: </form>
126:
127: </div>
128:
129: <div region="south" border="false" style="text-align: right; padding: 5px 5px 5px 0;">
130:
131: <a class="easyui-linkbutton" iconcls="icon-save" href="javascript:void(0)" onclick="javascript:submitForm();">
132:
133: 提交</a>
134:
135: </div>
136:
137: </div>
138:
139: <script type="text/javascript">
140:
141: $(function () {
142:
143: if (autoLoad == 1) {
144:
145: $('#txtPassword').keypress(function () {
146:
147: if ($(this).val().length > 0) {
148:
149: $('#txtPassword2').validatebox({
150:
151: required: true
152:
153: });
154:
155: }
156:
157: }).change(function () {
158:
159: if ($(this).val().length > 0) {
160:
161: $('#txtPassword2').validatebox({
162:
163: required: true
164:
165: });
166:
167: } else {
168:
169: $('#txtPassword2').validatebox({
170:
171: required: false
172:
173: });
174:
175: }
176:
177: });
178:
179:
180:
181: } else {
182:
183: $('#txtPassword,#txtPassword2').validatebox({
184:
185: required: true
186:
187: }); ;
188:
189: }
190:
191: });
192:
193: </script>
194:
窗口
窗口是用的非常頻繁的,顯示窗口:
1: $(function () {
2: $('body').append('<div id="myWindow" class="easyui-dialog" closed="true"></div>');
3: });
4: function showMyWindow(title, href, width, height, modal, minimizable, maximizable) {
5: $('#myWindow').window({
6: title: title,
7: width: width === undefined ? 600 : width,
8: height: height === undefined ? 400 : height,
9: content: '<iframe scrolling="yes" frameborder="0" src="' + href + '" style="width:100%;height:98%;"></iframe>',
10: // href: href === undefined ? null : href,
11: modal: modal === undefined ? true : modal,
12: minimizable: minimizable === undefined ? false : minimizable,
13: maximizable: maximizable === undefined ? false : maximizable,
14: shadow: false,
15: cache: false,
16: closed: false,
17: collapsible: false,
18: resizable: false,
19: loadingMessage: '正在加載數據,請稍等片刻......'
20: });
21: }
關閉窗口:
1: function closeMyWindow() {
2: $('#myWindow').window('close');
3: }
使用方式如下:
1: function onDataGridDblClickRow(rowIndex, rowData) {
2:
3: edit();
4:
5: }
6:
7: function addType() {
8:
9: showMyWindow('用戶管理 | 新建', '/WebPages/RoleManagement/AdminUser_Add.aspx', 600, 320)
10:
11: }
12:
13: function edit() {
14:
15: var row = $('#tt').datagrid('getSelected');
16:
17: if (row) {
18:
19: showMyWindow('用戶管理 | 編輯', '/WebPages/RoleManagement/AdminUser_Add.aspx?ID=' + row.ID + '&autoLoad=1', 600, 320)
20:
21: } else {
22:
23: showMsg("溫馨提示", "請選擇一行!");
24:
25: }
26:
27: }
窗口彈出有本頁彈出,有時由於框架頁太小,經常會使用頂層窗口彈出,如:
1: function showSetPicWindow(adname, id) {
2:
3: top.showMyWindow(adname + " | 廣告圖設置", '/WebPages/ADManagement/ADPicturesManagement.aspx?TypeCode=ADPictures&ID=' + id + '&ATCode=KTVAdvert', 707, 440);
4:
5: }
表單
一個系統總是不乏表單的,自然表單的提交與賦值自然是頻繁的。如果使用C#,可以通過反射減少工作量,但是我更趨向把工作量留給前臺。比如提交:
1: function submitForm(url) {
2: $('#ff').form('submit', {
3: url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
4: onSubmit: function () {
5: var flag = $(this).form('validate');
6: if (flag) {
7: showProcess(true, '溫馨提示', '正在提交數據...');
8: }
9: return flag
10: },
11: success: function (data) {
12: showProcess(false);
13: if (data == 1) {
14: top.showMsg('溫馨提示', '提交成功!');
15: if (parent !== undefined) {
16: if ($.isFunction(window.reloadParent)) {
17: reloadParent.call();
18: } else {
19: parent.$("#tt").datagrid('reload');
20: parent.closeMyWindow();
21: }
22: }
23: } else {
24: $.messager.alert('溫馨提示', data);
25: }
26: },
27: onLoadError: function () {
28: showProcess(false);
29: $.messager.alert('溫馨提示', '由於網絡或服務器太忙,提交失敗,請重試!');
30: }
31: });
32: }
值得說明的是:
- typeCode來自母版頁,爲頁面名。
- url爲提交的URL。
- onSubmit事件會觸發表單驗證,如果驗證通過會顯示提交進度遮罩層。如果覺得不夠用,可以自己擴展。
- success事件會關閉進度,如果提交成功會顯示成功提示,如果存在父窗口,會刷新父頁面DataGrid並且關閉當前窗口。當然也可以實現reloadParent函數來個性化處理。
- 表單id和DataGrid的id都是固定的,如果沒有效果請檢查id。
- 關於表單的這裏只寫了提交,賦值的代碼寫在母版頁了,以後再說。
頁面html的提交代碼如下:
1: <a class="easyui-linkbutton" iconcls="icon-save" href="javascript:void(0)" onclick="javascript:submitForm('/Ajax/ShortMMS_Common.ashx');">
2: 提交</a>
有些頁面可能刷新DataGrid還不夠,需要刷新頁面,於是可以使用下面的JS:
1: <script type="text/javascript">
2: function reloadParent() {
3: top.showProcess(false);
4: parent.showMsg('溫馨提示', '提交成功');
5: parent.document.location.reload();
6: }
7: </script>
最後,附上完整的JS代碼:
1: //時間格式化
2: Date.prototype.format = function (format) {
3: if (!format) {
4: format = "yyyy-MM-dd hh:mm:ss";
5: }
6: var o = {
7: "M+": this.getMonth() + 1, // month
8: "d+": this.getDate(), // day
9: "h+": this.getHours(), // hour
10: "m+": this.getMinutes(), // minute
11: "s+": this.getSeconds(), // second
12: "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
13: "S": this.getMilliseconds()
14: // millisecond
15: };
16: if (/(y+)/.test(format)) {
17: format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
18: }
19: for (var k in o) {
20: if (new RegExp("(" + k + ")").test(format)) {
21: format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
22: }
23: }
24: return format;
25: };
26: function fomatDate(str) {
27: return (new Date(parseInt(str.substring(str.indexOf('(') + 1, str.indexOf(')'))))).format("yyyy-MM-dd hh:mm:ss");
28: }
29: function showMsg(title, msg, isAlert) {
30: if (isAlert !== undefined && isAlert) {
31: $.messager.alert(title, msg);
32: } else {
33: $.messager.show({
34: title: title,
35: msg: msg,
36: showType: 'show'
37: });
38: }
39: }
40: $(function () {
41: $('body').append('<div id="myWindow" class="easyui-dialog" closed="true"></div>');
42: });
43: function showMyWindow(title, href, width, height, modal, minimizable, maximizable) {
44: $('#myWindow').window({
45: title: title,
46: width: width === undefined ? 600 : width,
47: height: height === undefined ? 400 : height,
48: content: '<iframe scrolling="yes" frameborder="0" src="' + href + '" style="width:100%;height:98%;"></iframe>',
49: // href: href === undefined ? null : href,
50: modal: modal === undefined ? true : modal,
51: minimizable: minimizable === undefined ? false : minimizable,
52: maximizable: maximizable === undefined ? false : maximizable,
53: shadow: false,
54: cache: false,
55: closed: false,
56: collapsible: false,
57: resizable: false,
58: loadingMessage: '正在加載數據,請稍等片刻......'
59: });
60: }
61: function closeMyWindow() {
62: $('#myWindow').window('close');
63: }
64: function submitForm(url) {
65: $('#ff').form('submit', {
66: url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
67: onSubmit: function () {
68: var flag = $(this).form('validate');
69: if (flag) {
70: showProcess(true, '溫馨提示', '正在提交數據...');
71: }
72: return flag
73: },
74: success: function (data) {
75: showProcess(false);
76: if (data == 1) {
77: top.showMsg('溫馨提示', '提交成功!');
78: if (parent !== undefined) {
79: if ($.isFunction(window.reloadParent)) {
80: reloadParent.call();
81: } else {
82: parent.$("#tt").datagrid('reload');
83: parent.closeMyWindow();
84: }
85: }
86: } else {
87: $.messager.alert('溫馨提示', data);
88: }
89: },
90: onLoadError: function () {
91: showProcess(false);
92: $.messager.alert('溫馨提示', '由於網絡或服務器太忙,提交失敗,請重試!');
93: }
94: });
95: }
96: function deleteConfirm() {
97: return showConfirm('溫馨提示', '確定要刪除嗎?');
98: }
99: function showConfirm(title, msg, callback) {
100: $.messager.confirm(title, msg, function (r) {
101: if (r) {
102: if (jQuery.isFunction(callback))
103: callback.call();
104: }
105: });
106: }
107: function showProcess(isShow, title, msg) {
108: if (!isShow) {
109: $.messager.progress('close');
110: return;
111: }
112: var win = $.messager.progress({
113: title: title,
114: msg: msg
115: });
116: }
117: