WebForm+三层,前台ajax(jquery),登录+显示列表(带有分页)(上篇)

登录页面层:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="_123.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <style>
        table {
            margin:0 auto;
            margin-top:20%;
        }
    </style>
    <script type="text/javascript">
        function check() {
            var struserid = $("#userid").val();
            var strpwd = $("#pwd").val();
        if (struserid == "") {
            alert("请输入账号!");
            return false;
        }
        if (strpwd == "") {
            alert("请输入密码!");
            return false;
            }
            var data = { UserID: struserid, Pwd: strpwd };
            $.ajax({
                url: "LoginHandler.ashx",
                type: "Post",
                data: data,
                success: function (result) {
                    debugger
                    if (result == "user") {
                        window.location.href = "hello.aspx";
                    }
                    else {
                        alert("账号或密码错误!");
                    }
                }
            })
        }
    //回车时,默认是登陆
    function on_return() {
        if (event.keyCode == 13) {
            check();
        }
    }
    </script>
</head>
<body onkeydown="on_return()">
    <form name ="loginForm" action="hello" runat="server">
        <table>
                <tr>
                    <td><label>账号:</label><input type="text" id="userid"/></td>
                </tr>
                <tr>
                    <td><label>密码:</label><input type="password" id="pwd"/></td>
                </tr>
                <tr>
                    <td style="text-align:center">
                        <input type="button" id="sub" value="确定" onclick='check()'/>
                        <input type="button" id="sub1" value="取消"/>
                    </td>
                </tr>
         </table>
    </form>
</body>
</html>
登录handler(一般处理程序)层
using BLL;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace _123
{
    /// <summary>
    /// LoginHandler 的摘要说明
    /// </summary>
    public class LoginHandler : IHttpHandler, IRequiresSessionState
    {
        
        public void ProcessRequest(HttpContext context)
        {
            string struserid = context.Request["UserID"].ToString();
            string strpwd = context.Request["Pwd"].ToString();

            UserInfo user = new UserInfo();
            UserInfoManager bll = new UserInfoManager();
            user = bll.Login(struserid, strpwd);

            string result = "";
            result = "ok";

            if (!string.IsNullOrEmpty(user.UserName))
            {
                context.Session["userinfo"] = user;
                if (user.UserType == 0)
                {
                    result = "user";
                }
                else if (user.UserType == 1)
                {
                    result = "manager";
                }
                else if (user.UserType == 2)
                {
                    result = "admin";
                }
            }
            else
            {
                result = "false";
            }
            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
登录实体层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Entity
{
    public class UserInfo
    {
        public string UserID { get; set; }
        public string UserName { get; set; }
        public int DeptID { get; set; }
        public string Password { get; set; }
        public string CallPhone { get; set; }
        public int UserType { get; set; }
        public int RowIndex { get; set; }
        public int TatalCount { get; set; }
        public string DeptName { get; set; }
        public string ckbDeptID { get; set; }
    }
}

登录服务层:
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace DAL
{
    public class UserInfoService
    {
        //登录
        public UserInfo Login(string UserID, string Pwd)
        {
            UserInfo ui = new UserInfo();
            string sql = string.Format("select*from UserInfo where UserID='{0}' and Password='{1}'", UserID, Pwd);
            DataTable dt = DBHelper.GetData(sql);
            if (dt.Rows.Count > 0)
            {
                ui.UserID = dt.Rows[0]["UserID"].ToString();
                ui.Password = dt.Rows[0]["Password"].ToString();
                if (!string.IsNullOrEmpty(dt.Rows[0]["DeptID"].ToString()))
                {
                    ui.DeptID = Convert.ToInt32(dt.Rows[0]["DeptID"]);
                }
                ui.UserName = dt.Rows[0]["UserName"].ToString();
                ui.UserType = Convert.ToInt32(dt.Rows[0]["UserType"].ToString());
            }
            return ui;
        }
    }
}

登录逻辑层:
using DAL;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    public class UserInfoManager
    {
        UserInfoService ui = new UserInfoService();
        public UserInfo Login(string UserID, string Pwd)
        {
            return ui.Login(UserID, Pwd);
        }
    }
}

列表页面层:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="hello.aspx.cs" Inherits="_123.hello" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script src="Scripts/jquery-3.3.1.min.js"></script>
    //引用bootstrap可以使页面拥有bootstrap的删格优点即随页面的变化而自适应变化
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <style>
        table tr th, table tr td {
            text-align:center;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            Getpagelist(1);
        })
        //加载列表
        function Getpagelist(obj) {
            var strPageSize = 5;//每页显示数目
            if (obj == "1") {
                strPageIndex = 1;
                $("#hidPageIndex").val(strPageIndex); ///第一次加载、点查询时
            } else {
                strPageIndex = $("#hidPageIndex").val();//当前页
            }

            $.ajax({
                url: "DepartmentHandler.ashx",
                type: "post",
                data: { type: "DeptPageList",pageIndex: strPageIndex, pageSize: strPageSize },
                //dataType: "json",

                success: function (result) {
                    //成功
                    $("#departmenttab").empty();
                    result = JSON.parse(result);
                    if (result.length > 0) {

                        var contentHtml = "<thead class='thead-dark'><tr><th scope='col'>序号</th><th scope='col'>部门名称</th><th scope='col'>主管</th><th scope='col'>操作</th></tr></thead>";

                        for (var i = 0; i < result.length; i++) {
                            //  contentHtml += "<tr><td style='width:80px'>" + (i + 1) + "</td>";
                            contentHtml += "<tbody><tr><td style='width:140px'>" + result[i]["RowIndex"] + "</td>";
                            contentHtml += "<td style='width:260px'>" + result[i]["DeptName"] + "</td>";
                            //contentHtml += "<td>" + result[i].ManagerID + "</td>";
                            contentHtml += "<td style='width:160px'>" + result[i]["UserName"] + "</td>";
                            contentHtml += "<td style='width:260px'>  <input id='hidDeptID" + i + "' type='hidden' value='" + result[i]["DeptID"] + "' />"
                                + "<a href='#' onclick='Load(" + i + ")'>编辑</a>" + "&nbsp;<a href='#' onclick='Delete(" + i + ")' > 删除</a></td></tr></tbody>";
                        }
                        $("#departmenttab").append(contentHtml);//追加html
                        $("#lblTotalCount").html(result[0]["TatalCount"]);
                    } else {
                        $("#lblTotalCount").html(0);//没有满足条件的数据时,总记录数应该为0
                    }
                }
            })
        }
         //上一页
        function last() {
            var sPageIndex = $("#hidPageIndex").val();
            sPageIndex--;
            if (sPageIndex <= 0) {
                alert("该页为第一页");
                return;
            }
            //sPageIndex = parseInt(sPageIndex) - 1;
            $("#hidPageIndex").val(sPageIndex);
            Getpagelist(0);
        }
        //下一页
        function next() {
            var sPageIndex = $("#hidPageIndex").val();
            var count = $("#lblTotalCount").text();
            var total;
            sPageIndex++;
            if (count % 5 == 0) {
                total = count / 5;
            }
            else {
                total = count / 5 + 1;
            }
            if (sPageIndex > total) {
                alert("该页为最后一页");
                return;
            }
            //sPageIndex = parseInt(sPageIndex) + 1;
            $("#hidPageIndex").val(sPageIndex);
            Getpagelist(0);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table id="departmenttab" class="table"></table>
            <input id="hidPageIndex" type="hidden" />
            总记录数:<label id="lblTotalCount"></label>
            &nbsp;&nbsp;
            <a href="#" onclick="last()">上一页</a>
            <a href="#" onclick="next()">下一页</a>
        </div>
    </form>
</body>
</html>

列表Handler(一般处理程序)层:
using BLL;
using Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _123
{
    /// <summary>
    /// DepartmentHandler 的摘要说明
    /// </summary>
    public class DepartmentHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //取前台传入的参数

            DepartmentManager bll = new DepartmentManager();
            Department deptInfo = new Department();

            string results = "";
            string type = context.Request["type"].ToString();//区分方法块

            if (type.ToUpper() == "DEPTPAGELIST")//部门分页列表
            {
                //处理分页逻辑
                int sPageIndex = int.Parse(context.Request["pageIndex"]);
                int sPageSize = int.Parse(context.Request["pageSize"]);

                Department dept = new Department();//传入实体参数

                int startIndex = (sPageIndex - 1) * sPageSize + 1;//开始数
                int endIndex = sPageIndex * sPageSize;//截止数

                List<Department> deptinfoList = new List<Department>();
                deptinfoList = bll.GetDeptPageList(dept, startIndex, endIndex);
                results = JsonConvert.SerializeObject(deptinfoList);//序列化成json

            }
            //输出到前台
            context.Response.Write(results);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
列表实体层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Entity
{
    public class Department
    {
        public int DeptID { get; set; }
        public string DeptName { get; set; }
        public string ManagerID { get; set; }
        public string DeptInfo { get; set; }
        public string UserInfo { get; set; }
        public string UserName { get; set; }
        public int RowIndex { get; set; }
        public int TatalCount { get; set; }
        public string UserID { get; set; }
    }
}

列表服务层
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DepartmentService
    {
        public List<Department> GetDeptPageList(Department deptInfo, int startIndex, int endIndex)
        {
            List<Department> deptList = new List<Department>();

            string strWhere1 = " ";   //不加where
            if (!string.IsNullOrEmpty(deptInfo.DeptName))
            {
                strWhere1 += "  and  deptname like '%" + deptInfo.DeptName + "%'";
            }
            if (!string.IsNullOrEmpty(deptInfo.ManagerID) && deptInfo.ManagerID != "0")
            {
                strWhere1 += "  and  managerid =" + deptInfo.ManagerID;
            }
            string sql = "select * from  (select ROW_NUMBER() over(order by a.Deptid) RowIndex ,a.*,b.UserName from Department a "
                + "left join UserInfo b on a.ManagerID=b.UserID where 1=1 " + strWhere1 + ") t where RowIndex between " + startIndex + " and " + endIndex + "" + strWhere1;

            DataTable dt = DBHelper.GetData(sql);

            #region 取总记录数

            string sql1 = "select count(*) totalCount from Department where 1=1 " + strWhere1;
            DataTable sdt = DBHelper.GetData(sql1);
            int totalCount = int.Parse(sdt.Rows[0]["totalCount"].ToString());

            #endregion

            for (int i = 0; i < dt.Rows.Count; i++)///把table转换成list<T>
            {
                Department info = new Department();
                info.DeptID = Convert.ToInt32(dt.Rows[i]["DeptID"]);
                info.DeptName = dt.Rows[i]["DeptName"].ToString();
                info.ManagerID = dt.Rows[i]["ManagerID"].ToString();
                info.DeptInfo = dt.Rows[i]["DeptInfo"].ToString();
                info.UserName = dt.Rows[i]["UserName"].ToString();
                info.RowIndex = int.Parse(dt.Rows[i]["RowIndex"].ToString());
                info.TatalCount = totalCount;
                deptList.Add(info);
            }

            return deptList;

        }
    }
}

列表逻辑层:
using DAL;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    public class DepartmentManager
    {
        DepartmentService dal = new DepartmentService();
        /// <summary>
        /// 部门分页列表
        /// </summary>
        /// <param name="deptInfo">传入的部门信息</param>
        /// <param name="pageIndex">查询开始数</param>
        /// <param name="endIndex">查询结束数量</param>
        /// <returns></returns>
        public List<Department> GetDeptPageList(Department deptInfo, int startIndex, int endIndex)
        {
            return dal.GetDeptPageList(deptInfo, startIndex, endIndex);
        }
    }
}

Web.config中需要写下如下代码用来链接当地数据库:
<connectionStrings>
    <add name="connStr" providerName="System.Data.SqlClient" connectionString="Data Source=.;Integrated Security=True;Initial Catalog=Attendance" />
  </connectionStrings>
服务层中还要添加DBHelper文件:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DBHelper
    {
        public static string connstr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        /// <summary>
        /// GetTable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetData(string sql)
        {
            DataTable dt = new DataTable();
            SqlConnection connection = new SqlConnection(connstr);
            SqlCommand command = new SqlCommand();
            connection.Open();
            SqlDataAdapter da = new SqlDataAdapter(sql, connection);
            da.Fill(dt);
            connection.Close();
            return dt;
        }
        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int CommData(string sql)
        {
            int result = 0;
            SqlConnection connection = new SqlConnection(connstr);
            connection.Open();
            SqlCommand command = new SqlCommand(sql, connection);
            result = command.ExecuteNonQuery();
            connection.Close();
            return result;
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值