JQuery EasyUi之界面設計——母版頁以及Ajax的通用處理(三)

前面介紹過JS了,就這樣個人認爲還不夠用。

因爲JS文件是死的,無法使用服務器代碼,自然不夠靈活。那麼通過母版頁就完善了這一點。那麼下面舉一個例子——控件賦值。

控件賦值

前面說過easyui的form自帶驗證、提交、重置與賦值,那麼如何利用這個賦值呢?千篇一律的寫賦值代碼總是那麼的令人厭煩,尤其是元素比較多的時候,用反射嘛又怕別人詬病,那麼就用JS來負責這一切吧.

那麼如何做到通用呢?那母版頁就是不錯的選擇。

下面貼出母版頁完整代碼:

   1: <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Form.master.cs" Inherits="Singer.Form" %>
   2:  
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4: <html xmlns="http://www.w3.org/1999/xhtml">
   5: <head runat="server">
   6:     <title></title>
   7:     <link href="/Scripts/jquery-easyui-1.2.5/themes/default/easyui.css" rel="stylesheet"
   8:         type="text/css" />
   9:     <link href="/Styles/form.css" rel="stylesheet" type="text/css" />
  10:     <link href="/Scripts/jquery-easyui-1.2.5/themes/icon.css" rel="stylesheet" type="text/css" />
  11:     <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
  12:     <script src="/Scripts/jquery-easyui-1.2.5/jquery.easyui.min.js" type="text/javascript"></script>
  13:     <script src="/Scripts/jquery-easyui-1.2.5/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
  14:     <script src="/Scripts/common.js" type="text/javascript"></script>
  15:     <asp:ContentPlaceHolder ID="head" runat="server">
  16:     </asp:ContentPlaceHolder>
  17: </head>
  18: <body>
  19:     <script type="text/javascript">
  20:         var ajaxUrl = '/Ajax/Common.ashx';
  21:         //表單ID
  22:         var id = '<%=Request.QueryString["ID"] %>';
  23:         //是否自動加載表單,編輯用
  24:         var autoLoad = '<%=Request.QueryString["autoLoad"] %>';
  25:         //Ajax類型【頁面名】
  26:         var typeCode = "<%=System.IO.Path.GetFileName(HttpContext.Current.Request.Path) %>";
  27:         $(function () {
  28:             if ($.isFunction(window.setAjaxUrl)) {
  29:                 setAjaxUrl.call();
  30:             }
  31:             //加載數據
  32:             if (autoLoad == 1 && id !== undefined && id != '') {
  33:                 $('#ff').form('load', ajaxUrl + '?autoLoad=1&Type=' + typeCode + '&id=' + id + "&_" + Math.floor(Math.random() * (1000 + 1)));
  34:  
  35:             }
  36:         });
  37:     </script>
  38:     <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
  39:     </asp:ContentPlaceHolder>
  40: </body>
  41: </html>

從代碼中可以看出:

  1. 頁面上定義了3個全局JS變量,有註釋,我就不贅述了。
  2. setAjaxUrl函數在表單賦值加載前執行,可以實現用於更改上面的3個變量的值,或者作其他作用,建議命名爲beforeFormLoad。
  3. typeCode的值爲頁面名,比如“index.aspx”,提交給處理程序用於判斷是哪個頁面,以便返回對應的JSON數據。

 

後臺處理邏輯

那麼處理程序如何返回對應的JSON數據呢?先看看大體結構:

image

   1: case "ADMINUSER_ADD.ASPX":
   2:     #region 用戶添加
   3:     {
   4:         if (context.Request["autoLoad"] == "1")
   5:             context.Response.Write(db.TB_Admin.FirstOrDefault(p => p.ID == Convert.ToInt32(context.Request["id"])).ToJson());
   6:         else
   7:         {
   8:             if (context.Request["id"].IsEmpty())
   9:             {
  10:                 if (context.Request["AdminPassword"].Trim() == string.Empty)
  11:                 {
  12:                     context.Response.Write("請輸入密碼!!");
  13:                     return;
  14:                 }
  15:                 if (context.Request["AdminPassword"] != context.Request["AdminPassword2"])
  16:                 {
  17:                     context.Response.Write("兩次密碼不一致!!");
  18:                     return;
  19:                 }
  20:                 var isExist = db.TB_Admin.FirstOrDefault(p => p.AdminLogin == context.Request["AdminLogin"].Trim());
  21:                 if (isExist != null)
  22:                 {
  23:                     context.Response.Write("用戶名重複!!");
  24:                     return;
  25:                 }
  26:                 TB_Admin singer = new TB_Admin()
  27:                 {
  28:                     Defatulflag = context.Request["Defatulflag"] == "1" ? 1 : 0,
  29:                     AdminLogin = context.Request["AdminLogin"].Trim(),
  30:                     CreateBy = userID.ToString(),
  31:                     CreateDate = DateTime.Now,
  32:                     LastLoginDate = null,
  33:                     Password = Utility.UserINFOManager.PasswordEncry(context.Request["AdminPassword"].Trim()),
  34:                     RoleID = Convert.ToInt32(context.Request["RoleID"])
  35:                 };
  36:                 db.TB_Admin.InsertOnSubmit(singer);
  37:                 db.SubmitChanges();
  38:             }
  39:             else
  40:             {
  41:                 var isExist = db.TB_Admin.FirstOrDefault(p => p.ID == Convert.ToInt32(context.Request["id"]));
  42:                 isExist.Defatulflag = context.Request["Defatulflag"] == "1" ? 1 : 0;
  43:                 isExist.AdminLogin = context.Request["AdminLogin"].Trim();
  44:                 isExist.RoleID = Convert.ToInt32(context.Request["RoleID"]);
  45:                 if (context.Request["AdminPassword"].Trim() != string.Empty)
  46:                     isExist.Password = Utility.UserINFOManager.PasswordEncry(context.Request["AdminPassword"].Trim());
  47:                 db.SubmitChanges();
  48:             }
  49:             context.Response.Write("1");
  50:             return;
  51:         }
  52:     }
  53:     break;
  54:     #endregion

從上面代碼可以看出:

    1. 通過Type參數,可以獲取請求的頁面。
    2. 通過autoLoad參數,可以判斷是否是加載賦值。注意FirstOrDefault函數,是獲取第一條數據,然後通過ToJson方法(自己定義的擴展方法)轉換爲JSON數據。
    3. 通過id參數,可以判斷是否爲編輯。
    4. 以上使用的是LINQ to SQL,個人認爲使用LINQ to SQl開發小項目還是挺快的。關於LINQ to SQL的具體使用,就不說了。順便送大家一段服務器分頁通用代碼(僅支持LINQ2SQL),如果覺得性能不行,請自己用存儲過程實現,這裏不考慮性能:
   1: /// <summary>
   2: /// 當前頁
   3: /// </summary>
   4: private int pageIndex = Convert.ToInt32(HttpContext.Current.Request["page"] ?? "1");
   5: /// <summary>
   6: /// 每頁顯示記錄數
   7: /// </summary>
   8: private int pageSize = Convert.ToInt32(HttpContext.Current.Request["rows"] ?? "1");
   9: /// <summary>
  10: /// 獲取分頁JSON
  11: /// </summary>
  12: /// <typeparam name="T"></typeparam>
  13: /// <param name="data"></param>
  14: /// <returns></returns>
  15: private string GetPageingJson<T>(IQueryable<T> data)
  16: {
  17:     return string.Format("{{\"total\":\"{0}\",\"rows\":{1}}}", data.Count(), data.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToJson());
  18: }
  1. 相比使用各種.NET Ajax框架,我還是喜歡按上面這種模式,雖然很多Ajax框架可以實現js調用C#方法,可以調用WebService,可以操作服務器控件,但是我仍然癡迷上面的模式,因爲個人覺得這樣精簡、易控制、一目瞭然、沒有ViewState、沒有服務器控件、甚至沒有Cookie和Session(需要實現接口)。。。。

 

前端HTML

剛纔貼的後臺處理邏輯是用戶管理的編輯界面,那麼前端HTML呢?如下:

   1: <%@ Page Title="" Language="C#" MasterPageFile="~/Form.Master" AutoEventWireup="true"
   2:     CodeBehind="AdminUser_Add.aspx.cs" Inherits="Singer.WebPages.RoleManagement.AdminUser_Add" %>
   3:  
   4: <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
   5: </asp:Content>
   6: <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
   7:     <div class="easyui-layout" style="text-align: left; height: 270px;" fit="true">
   8:         <div region="center" border="false" style="padding: 10px; background: #fff; border: 1px solid #ccc;">
   9:             <form id="ff" method="post">
  10:             <input type="hidden" name="id" value="<%=Request.QueryString["ID"] %>" />
  11:             <table border="0" cellpadding="0" cellspacing="0">
  12:                 <tr>
  13:                     <td>
  14:                         <label for="AdminLogin">
  15:                             登錄名:</label>
  16:                     </td>
  17:                     <td>
  18:                         <input class="easyui-validatebox" style="width: 300px;" type="text" required="true"
  19:                             validtype="length[0,20]" name="AdminLogin"></input>
  20:                     </td>
  21:                 </tr>
  22:                 <tr>
  23:                     <td>
  24:                         <label for="RoleID">
  25:                             所屬角色:</label>
  26:                     </td>
  27:                     <td>
  28:                         <input class="easyui-combobox" valuefield="ID" textfield="RoleName" panelheight="auto"
  29:                             editable="false" style="width: 300px;" url="/Ajax/Common.ashx?Type=GetRoles"
  30:                             required="true" name="RoleID"></input>
  31:                     </td>
  32:                 </tr>
  33:                 <tr>
  34:                     <td colspan="2" style='color: Red'>
  35:                         在編輯時,輸入管理員密碼錶示重新設置密碼。
  36:                     </td>
  37:                 </tr>
  38:                 <tr>
  39:                     <td>
  40:                         <label for="AdminPassword">
  41:                             密碼:</label>
  42:                     </td>
  43:                     <td>
  44:                         <input class="easyui-validatebox" style="width: 300px;" type="text" validtype="length[6,20]"
  45:                             id='txtPassword' name="AdminPassword"></input>
  46:                     </td>
  47:                 </tr>
  48:                 <tr>
  49:                     <td>
  50:                         <label for="AdminPassword2">
  51:                             確認密碼:</label>
  52:                     </td>
  53:                     <td>
  54:                         <input class="easyui-validatebox" style="width: 300px;" type="text" validtype="length[6,20]"
  55:                             id='txtPassword2' name="AdminPassword2"></input>
  56:                     </td>
  57:                 </tr>
  58:                 <tr>
  59:                     <td>
  60:                         <label for="Defatulflag">
  61:                             是否上架:</label>
  62:                     </td>
  63:                     <td>
  64:                         <input type="checkbox" name="Defatulflag" class="easyui-validatebox" type="text"
  65:                             required="true" value="1" />
  66:                     </td>
  67:                 </tr>
  68:             </table>
  69:             </form>
  70:         </div>
  71:         <div region="south" border="false" style="text-align: right; padding: 5px 5px 5px 0;">
  72:             <a class="easyui-linkbutton" iconcls="icon-save" href="javascript:void(0)" οnclick="javascript:submitForm();">
  73:                 提交</a> <%--<a class="easyui-linkbutton" iconcls="icon-no" href="javascript:void(0)" οnclick="$('#ff').form('clear');">
  74:                     重置</a>--%>
  75:         </div>
  76:     </div>
  77:     <script type="text/javascript">
  78:         $(function () {
  79:             if (autoLoad == 1) {
  80:                 $('#txtPassword').keypress(function () {
  81:                     if ($(this).val().length > 0) {
  82:                         $('#txtPassword2').validatebox({
  83:                             required: true
  84:                         });
  85:                     }
  86:                 }).change(function () {
  87:                     if ($(this).val().length > 0) {
  88:                         $('#txtPassword2').validatebox({
  89:                             required: true
  90:                         });
  91:                     } else {
  92:                         $('#txtPassword2').validatebox({
  93:                             required: false
  94:                         });
  95:                     }
  96:                 });
  97:  
  98:             } else {
  99:                 $('#txtPassword,#txtPassword2').validatebox({
 100:                     required: true
 101:                 }); ;
 102:             }
 103:         });
 104:     </script>
 105: </asp:Content>

值得注意的是:

  1. 這裏使用的控件均爲HTML控件。
  2. 請注意name屬性,該屬性決定提交的post參數名,同時也是form加載賦值的參數名,也就是這裏的值要與後臺輸出的JSON要對應。
  3. 返回的JSON數據如下:
  4. image
發佈了42 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章