前面介绍过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>
从代码中可以看出:
- 页面上定义了3个全局JS变量,有注释,我就不赘述了。
- setAjaxUrl函数在表单赋值加载前执行,可以实现用于更改上面的3个变量的值,或者作其他作用,建议命名为beforeFormLoad。
- typeCode的值为页面名,比如“index.aspx”,提交给处理程序用于判断是哪个页面,以便返回对应的JSON数据。
后台处理逻辑
那么处理程序如何返回对应的JSON数据呢?先看看大体结构:
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
从上面代码可以看出:
-
- 通过Type参数,可以获取请求的页面。
- 通过autoLoad参数,可以判断是否是加载赋值。注意FirstOrDefault函数,是获取第一条数据,然后通过ToJson方法(自己定义的扩展方法)转换为JSON数据。
- 通过id参数,可以判断是否为编辑。
- 以上使用的是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: }
- 相比使用各种.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)" onclick="javascript:submitForm();">
73: 提交</a> <%--<a class="easyui-linkbutton" iconcls="icon-no" href="javascript:void(0)" onclick="$('#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>
值得注意的是:
这一篇就写到这里吧。由于最近忙,又耽误了。。。