zoukankan      html  css  js  c++  java
  • WEB简单数据操作练习

     主要学习代码:

    Login.aspx:

        <!--第一种方式-->
        <%--  <script type="text/javascript">
            function Go() {
                var name = document.getElementById("txtName");
                var pwd = document.getElementById("txtPwd");
                var code = document.getElementById("txtCode");
                if (name.value == "") {
                    alert("请输入用户名");
                }
                else if (pwd.value == "") {
                    alert("请输入密码");
                }
                else if (code.value == "") {
                    alert("请输入验证码");
                }
                else {
                    //哈哈,不知道怎么了这里用不了链式编程了
                    var btn = document.getElementById("btnLogin");
                    btn.setAttribute("type", "submit");
                    btn.onsubmit;
                }
            };
        </script>--%>
        <script type="text/javascript">
            function Go() {
                var name = document.getElementById("txtName");
                var pwd = document.getElementById("txtPwd");
                var code = document.getElementById("txtCode");
                if (name.value == "") {
                    alert("请输入用户名");
                    return false;
                }
                else if (pwd.value == "") {
                    alert("请输入密码");
                    return false;
                }
                else if (code.value == "") {
                    alert("请输入验证码");
                    return false;
                }
                return true;
            };
        </script>
        <style type="text/css">
            .input {
                font-size: 16px;
                width: 150px;
                margin: 3px;
                vertical-align: text-bottom;
            }
        </style>
    </head>
    <body>
        <div id="Login" style=" 350px; height: 150px; background-color: #00ff21; padding: 5px; position:fixed;top:50%;left:50%;margin:-100px 0 0 -175px;">
            <form method="post" action="Login.aspx">
                用户名:<input class="input" type="text" name="txtName" id="txtName" /><br />&nbsp;&nbsp;码:<input class="input" type="password" name="txtPwd" id="txtPwd" /><br />
                验证码:<input class="input" type="text" name="txtCode" id="txtCode" /><img src="VerifyCode.ashx" onclick="this.src='VerifyCode.ashx?times='+new Date();" title="点击更换验证码" alt="验证码" style="height: 40px; margin-left: 10px;" /><br />
                <div style="float: left; margin: 8px;">
                    <!--第一种方式-->
                    <%--<input type="button" value="登录" id="btnLogin" onclick="Go()"/>--%><!--不能用submit作为名字--><input type="checkbox" name="chkAuto" id="chkAuto" /><label for="chkAuto">一周内自动登录</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="登录" onclick="return Go()" style="margin-right: 18px; float: right;" />
                </div>
            </form>
        </div>
    </body>

    Login.aspx.cs

    public partial class Login : System.Web.UI.Page
    {
        Web.BLL.TransferAction action = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            //刷新登录。。。
            string name, code, pwd;
            code = Request.Form["txtCode"];
            if (null == Request.Cookies["cName"] && Request.Cookies["cPwd"] == null)
            {
                if (code != null)
                {
                    if (code == Session["code"].ToString().ToLower())
                    {
            name = Request.Form["txtName"];
                        pwd = Request.Form["txtPwd"];
                        action = new Web.BLL.TransferAction();
                        if (action.IsExist(name, pwd))
                        {
                            if (Request.Form["chkAuto"] != null)//选中 on
                            {
                                //实际(加密[user+Identity+key+...])并不是这样实现自动登录的,只是简单原理仅供学习。
                                HttpCookie cookieName = new HttpCookie("cName", name);
                                HttpCookie cookiePwd = new HttpCookie("cPwd");
                                cookiePwd.Value = pwd;
                                cookiePwd.Expires = DateTime.Now.AddMinutes(10);
                                cookieName.Expires = DateTime.Now.AddMinutes(10);
                                Response.Cookies.Add(cookieName);
                                Response.Cookies.Add(cookiePwd);//已经向浏览器发送了Cookie。
                            }
                            Session["name"] = name;
                            // Response.Cookies.Add(cookiePwd);后UrlReferrer不为null
                            Response.Redirect("List.aspx");
                        }
                        else
                        {
                            Response.Write("<script>alert("用户名或密码错误。");</script>");
                        }
                    }
                    else
                    {//向浏览器输出js脚本
                        //// 第一个参数产生随机键
                        //但是必须是<form runat="server" />
                        //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), "alert("验证码错误。");", true);
                        //Page.ClientScript.registerstartupscript(this.gettype(), guid.newguid().tostring(), "alert("验证码错误。");", true);
                        Response.Write("<script>alert('验证码错误')</script>");
                    }
                }
            }
            else
            {
                action = new Web.BLL.TransferAction();
                if (action.IsExist(Request.Cookies["cName"].Value, Request.Cookies["cPwd"].Value))
                {
                    Session["name"] = Request.Cookies["cName"].Value;
                    //这里没有向浏览器输出任何东西,所以List的UrlReferrer为null
                    //Response.Redirect("List.aspx");
                    //所以不用上面的用下面的
                    Response.Write("自动登录成功,<span id='span' style="color:red;">3</span> 秒后跳转。<script>var sec=2; setInterval(function (){if(sec<0){window.location='List.aspx';}else{document.getElementById("span").innerHTML=sec;sec--;}},1000);</script>");
                    //停止执行页面。
                    Response.End();
                }
                else
                {
                    Response.Write("<script>alert("自动登录失败,请手动登录.");</script>");
                }
            }
        }
    }

    List.aspx

       <style type="text/css">
            .head {
                width: 250px;
                margin: 30px auto;
            }
    
            table {
                border-left: 1px solid #000;
                border-top: 1px solid #000;
                margin: 10px auto;
                padding: 0px;
                width: 500px;
                text-align: center;
            }
    
            td {
                border-right: 1px solid #000;
                border-bottom: 1px solid #000;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <form id="form1">
            <div class="head">姓名:<%=Web.Model.Users.USER!=null?Web.Model.Users.USER.Name:"" %> &nbsp;&nbsp;&nbsp;&nbsp;学号:<%=Web.Model.Users.USER!=null?Web.Model.Users.USER.Num:"" %></div>
            <div>
                <table cellspacing="0">
                    <tr>
                        <td>ID</td>
                        <td>C#</td>
                        <td>SQL</td>
                        <td>ASP.NET</td>
                        <td>Edit</td>
                    </tr>
                    <%Response.Write(sb.ToString()); %>
                </table>
            </div>
        </form>
    </body>

    List.aspx.cs

     public System.Text.StringBuilder sb = new System.Text.StringBuilder(100);
    
        protected void Page_Load(object sender, EventArgs e)
        {
            
            //window.location=下有UrlReferrer吗? 答案:YES
            if (Session["name"] != null && Request.UrlReferrer.ToString().Contains("Login.aspx"))
            {
                sb.Append("<tr><td>");
                sb.Append(Web.Model.Users.USER.ID.ToString());
                sb.Append("</td><td>");
                if (Web.Model.Users.USER.sNUM != null)
                {
                    sb.Append(Web.Model.Users.USER.sNUM.CSharp == null ? "" : Web.Model.Users.USER.sNUM.CSharp.ToString());
                    sb.Append("</td><td>");
                    sb.Append(Web.Model.Users.USER.sNUM.SQL == null ? "" : Web.Model.Users.USER.sNUM.SQL.ToString());
                    sb.Append("</td><td>");
                    sb.Append(Web.Model.Users.USER.sNUM.ASPNET == null ? "" : Web.Model.Users.USER.sNUM.ASPNET.ToString());
                }
                else
                {
                    sb.Append("</td><td></td><td>");
                }
                sb.Append("</td><td>");
                sb.Append("<a href='Edit.aspx?access=" + Web.Model.Users.USER.Access + "'>编辑</a>");
                sb.Append("</td></tr>");
            }
            else
            {
                Response.Redirect("Forbidden.aspx");
            }
        }

    Modify.aspx.cs

      private Web.BLL.TransferAction action = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.UrlReferrer != null && Request.UrlReferrer.ToString().Contains("Edit.aspx?access="))
            {
                int result = 0;
                //提交表单时有空的情况?
                //管理员
                string name = Request.Form["txtMName"];
                string pwd = Request.Form["txtMPwd"];
                string num = Request.Form["txtMNum"];
                //用户
                string access = Request.Form["txtMAccess"];
                //Score
                string csharp = Request.Form["txtMCSharp"];
                string sql = Request.Form["txtMSQL"];
                string aspnet = Request.Form["txtMASPNET"];
                //id
                string id = Request.Form["id_Modify"];
                //
                if (csharp == null)
                {
                    Web.Model.Users user = new Web.Model.Users();
                    user.Name = name;
                    user.Pwd = pwd;
                    user.Num = num;
                    user.Access = access == null ? null : (bool?)(bool.Parse((access == "0" ? "false" : "true")));
                    user.ID = int.Parse(id);
                    action = new Web.BLL.TransferAction();
                    //重点:
                    //事实上你修改了用户密码:要重新向客户端重置Cookie
                    result = action.Modify(user);
                    if (result == 1)
                    {
                        HttpCookie cname = new HttpCookie("cName", num);
                        HttpCookie cpwd = new HttpCookie("cPwd", pwd);
                        cname.Expires = DateTime.Now.AddHours(7);
                        cpwd.Expires = DateTime.Now.AddHours(7);
                        Response.Cookies.Add(cname);
                        Response.Cookies.Add(cpwd);
                    }
                }
                else
                {
                    Web.Model.Score score = new Web.Model.Score();
                    score.CSharp = csharp == "" ? null : (int?)int.Parse(csharp);
                    score.SQL = sql == "" ? null : (int?)int.Parse(sql);
                    score.ASPNET = aspnet == "" ? null : (int?)int.Parse(aspnet);
                    score.ID = int.Parse(id);
                    action = new Web.BLL.TransferAction();
                    result = action.Modify(score);
                }
                //action = new Web.BLL.TransferAction();
                if (result == 1)
                {
                    Response.Write("数据修改成功,<span id="sInfo" style="color:red;">3</span>秒后,自动跳转。<script>var s=3;setInterval(function(){if(s<0){window.location='Edit.aspx?access=true';}else{document.getElementById("sInfo").innerHTML=s;s--;}},1000);</script>");
                }
                else
                {
                    //数据插入失败。
                    Response.Write("数据修改失败,<span id="sInfo" style="color:red;">3</span>秒后,自动跳转。<script>var s=3;setInterval(function(){if(s<0){window.location='Edit.aspx?access=true';}else{document.getElementById("sInfo").innerHTML=s;s--;}},1000);</script>");
                }
            }
            else
            {
                Response.Redirect("Forbidden.aspx");
            }
        }

    Edit.aspx

      <style type="text/css">
            div p {
                font-size: xx-large;
                color: #ff006e;
                text-align: center;
            }
    
            table {
                /*border-left: 1px solid #000;
                border-top: 0px solid #000;*/
                border: none;
                margin: 0px auto;
                padding: 3px;
            }
    
            td {
                border-left: 1px solid #000;
                border-right: 1px solid #000;
                border-bottom: 1px solid #f00;
                padding: 5px;
                text-align: center;
                width: 100px;
            }
        </style>
        <script type="text/javascript">
            function Show() {
                document.getElementById(arguments[0]).style.display = "block";
            };
            function Cancel(id) {
                document.getElementById(id).style.display = "none";
            };
            function Del(id) {
                //这里没有AJAX的异步请求滴。很假很假的模拟。
                if (confirm("确定删除吗?")) {
                    window.location = "Del.aspx?id=" + id;
                }
            };
            function tbl(innerHtml) {
                document.getElementById("tbl").innerHTML = innerHtml;
            };
            function GO() {
                //3个公共的输入框
                if (document.getElementById(arguments[0]).value == "") {
                    alert("请输入名字"); return false;
                }
                if (document.getElementById(arguments[1]).value == "") {
                    alert("请输入密码"); return false;
                }
                if (document.getElementById(arguments[2]).value == "") {
                    alert("请输入学号"); return false;
                }
                //非管理员的修改/添加用户
                if (arguments.length == 4 || document.getElementById("txtMAccess")) {//
                    var c = true;
                    if (arguments[3] != "txtAccess") {
                        if (document.getElementById("txtMAccess").value == "")
                            c = false;
                    }
                    else {//添加用户
                        if (document.getElementById("txtAccess").value == "")
                            c = false;
                    }
                    if (!c) {
                        alert("请输入权限"); return false;
                    }
                }
                return true;
            };
            //可行否?:href='javascript:Show();GetTrObj();';//答案:YES。
            //弹出层显示
            function GetTrObj() {
                var tr, innerHtml;
                if (arguments[0] == "u") {//u:用户
                    innerHtml = <%=tblU %>
                    tr = document.getElementById("u" + arguments[1]);
                    if (tr.childNodes[tr.childElementCount - 2].textContent == "0") {//非管理员,没有设计对管理员的权限修改
                        innerHtml += <%=tblUAdd%>
                        tbl(innerHtml);
                        document.getElementById("txtMAccess").value = 0;
                    }
                    else
                        tbl(innerHtml);
                    document.getElementById('txtMName').value = tr.childNodes.item(1).textContent;
                    document.getElementById('txtMPwd').value = tr.children.item(2).innerHTML;
                    document.getElementById('txtMNum').value = tr.childNodes[3].innerText;
                    //给事件动态传递参数
                    //提取修改 管理员3个 用户4个 的公共输入框不能为空。
                    document.getElementById("sub").onclick = function () { return GO('txtMName', 'txtMPwd', 'txtMNum'); };
                }
                else {//s:成绩
                    innerHtml = <%=tblS%>
                    tr = document.getElementById("s" + arguments[1]);
                    tbl(innerHtml);
                    document.getElementById('txtMCSharp').value = tr.childNodes.item(2).textContent;
                    document.getElementById('txtMSQL').value = tr.children.item(3).innerHTML;
                    document.getElementById('txtMASPNET').value = tr.childNodes[4].innerText;
                    //Score修改
                    //因为成绩是可为null 可以直接submit->post  不用GO验证
                }
                //表单ID
                document.getElementById("id_Modify").value = arguments[1];
            };
        </script>
    </head>
    <body>
        <!--none-->
        <input type="hidden" value="<%=json %>" />
        <div id="hidden" style="display: none;">
            <div>
                <p>管理员编辑页面</p>
            </div>
            <form id="form1">
                <table cellspacing="0" style="margin-top: 60px;">
                    <tr style="border-bottom: 1px; padding: 10px;">
                        <td colspan="5" style="text-align: left; padding-left: 60px; padding-bottom: 15px; border-right: none; border-left: none;">管理员:&nbsp;<%=(Web.Model.Users.USER!=null&&access!=null)?Web.Model.Users.USER.Name:"" %></td>
                        <td style="text-align: center; padding-bottom: 15px; border-right: none; border-left: none;"><a href="javascript:Show('Add');">添加</a></td>
                    </tr>
                    <tr>
                        <td>ID</td>
                        <td>Name</td>
                        <td>Pwd</td>
                        <td>Number</td>
                        <td>Access</td>
                        <td>编辑</td>
                    </tr>
                    <%=sbUser %>
                </table>
                <table cellspacing="0" style="margin-top: 80px;">
                    <tr>
                        <td colspan="6" style="text-align: center; padding-bottom: 15px; border-left: none; border-right: none;">成绩列表</td>
                    </tr>
                    <tr>
                        <td>ID</td>
                        <td>Number</td>
                        <td>C#</td>
                        <td>SQL</td>
                        <td>ASP.NET</td>
                        <td>编辑</td>
                    </tr>
                    <%=sbScore %>
                </table>
            </form>
        </div>
        <!--Add-->
        <div id="Add" style=" 500px; height: 170px; top: 50%; left: 50%; margin: -100px 0 0 -250px; position: fixed; display: none; z-index: 101; background-color: #808080; opacity: 0.9;">
            <br />
            <!--什么也没写到本页面-->
            <form action="Add.aspx" method="post" id="frmAdd">
                <div style="text-align: center; padding: 10px;">
                    姓名:<input type="text" name="txtName" id="txtName" />
                    密码:<input type="text" name="txtPwd" id="txtPwd" /><br />
                    学号:<input type="text" name="txtNum" id="txtNum" />
                    权限:<input type="text" name="txtAccess" id="txtAccess" value="0" /><br />
                    &nbsp;&nbsp;&nbsp;C#:<input type="text" name="txtCSharp" id="txtCSharp" />
                    &nbsp;SQL:<input type="text" name="txtSQL" id="txtSQL" /><br />
                    ASP.Net:<input type="text" name="txtASPNET" id="txtASPNET" />
                </div>
                <div style=" auto; float: right; margin: 10px auto; padding: 2px;">
                    <!--添加7个输入框 参数中的4个不能为空-->
                    <input type="submit" value="确定" id="btnOK" onclick="return GO('txtName', 'txtPwd', 'txtNum', 'txtAccess')" />&nbsp;&nbsp;<input type="button" value="取消" id="btnCancel" onclick="    javascript: Cancel('Add');" />&nbsp;&nbsp;
                </div>
            </form>
        </div>
        <!--Modify-Admin-->
        <div id="A_Modify" style="display: none;  300px; height: 180px; background-color: #0b9b05; opacity: 0.9; left: 50%; top: 50%; margin: -90px 0 0 -150px; position: fixed;">
            <form action="Modify.aspx" method="post">
                <input type="hidden" name="id_Modify" id="id_Modify" />
                <div id="tbl" style=" 202px; height: auto; margin: 0 auto; padding-top: 28px;">
                </div>
                <div style="margin-top: 20px; float: right; margin-right: 40px;">
                    <input type="submit" value="确定" id="sub" />
                    <input type="button" value="取消" onclick="javascript: Cancel('A_Modify');" />
                </div>
            </form>
        </div>
        <div style="text-align: center; bottom: 10px; margin-top: 100px;">
            <span>管理员请谨慎操作</span>
        </div>
    </body>

    Edit.aspx.cs

        protected string json;
        public string tblU = "'姓名:<input type="text" name="txtMName" id="txtMName"/><br />密码:<input type="text" name="txtMPwd" id="txtMPwd" /><br />学号:<input type="text" name="txtMNum" id="txtMNum" /><br />';";
        public string tblUAdd="'权限:<input type="text" name="txtMAccess" id="txtMAccess" /><br />';";
        public string tblS = "'C#:<input type="text" name="txtMCSharp" id="txtMCSharp"/><br />SQL:<input type="text" name="txtMSQL" id="txtMSQL"/><br />ASP.NET:<input type="text" name="txtMASPNET" id="txtMASPNET" /><br />';";
        private List<Web.Model.Users> lsUsers = null;
        public Dictionary<int, Web.Model.Users> dUS = null;
        public object access = null;
        public System.Text.StringBuilder sbUser, sbScore;
        private Web.BLL.TransferAction action = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            access = Request.QueryString["access"];
            //这里为什么一直请求。
            if (access != null && bool.Parse(access.ToString()) == true && Request.UrlReferrer != null)
            {
                //显示body
                Response.Write("<script>window.onload=function(){document.getElementById("hidden").style.display = "block";};</script>");
                action = new Web.BLL.TransferAction();
                //1.得到所有的Users和Score
                lsUsers = action.GetUsers();
    
                //JavaScriptSerializer js = new JavaScriptSerializer();
                //json = js.Serialize(lsUsers);
                // JavaScriptConverter
                if (lsUsers != null)
                {
                    sbUser = new System.Text.StringBuilder(300);
                    sbScore = new System.Text.StringBuilder(500);
                }
                foreach (Web.Model.Users item in lsUsers)
                {
                    //为获取tr对象
                    sbUser.Append("<tr id="u" + item.ID + ""><td>");
                    sbUser.Append(item.ID);
                    sbUser.Append("</td><td>");
                    sbUser.Append(item.Name);
                    sbUser.Append("</td><td>");
                    sbUser.Append(item.Pwd);
                    sbUser.Append("</td><td>");
                    sbUser.Append(item.Num);
                    sbUser.Append("</td><td>");
                    if (item.Access == true)
                    {
                        sbUser.Append(1);
                        sbUser.Append("</td><td>");
                        //管理员的话没有删除。假定只有一个管理员,
                        //扩展的话可以修改Access:但是
                        //查询出来的Access==true的count必须大于1
                        sbUser.Append("<a href='javascript:Show("A_Modify"," + item.ID + ");GetTrObj("u"," + item.ID + ");'>修改</a>");
                    }
                    else
                    {
                        sbUser.Append(0);
                        sbUser.Append("</td><td>");
                        sbUser.Append("<a href='javascript:Show("A_Modify"," + item.ID + ");GetTrObj("u"," + item.ID + ");'>修改</a>&nbsp;&nbsp;<a href='javascript:Del(" + item.ID + ");'>删除</a>");
                    }
                    sbUser.Append("</td></tr>");
                    if (item.sNUM != null)
                    {
                        sbScore.Append("<tr id="s" + item.sNUM.ID + ""><td>");
                        sbScore.Append(item.sNUM.ID);
                        sbScore.Append("</td><td>");
                        sbScore.Append(item.sNUM.Number);
                        sbScore.Append("</td><td>");
                        sbScore.Append(item.sNUM.CSharp);
                        sbScore.Append("</td><td>");
                        sbScore.Append(item.sNUM.SQL);
                        sbScore.Append("</td><td>");
                        sbScore.Append(item.sNUM.ASPNET);
                        sbScore.Append("</td><td>");
                        sbScore.Append("<a href='javascript:Show("A_Modify"," + item.ID + ");GetTrObj("s"," + item.sNUM.ID + ");'>修改</a>");
                        // sbScore.Append("</td><td>");
                        sbScore.Append("</td></tr>");
                    }
                }
                // dUS = action.GetUsersAndScore();
                //2.连接成字符串显示
    
            }
            else
            {
                //用一个公用方法更好。
                Response.Write("请用管理员身份登录,<span id='span' style="color:red;">3</span> 秒后回到登录页面。<script>var sec=2; setInterval(function (){if(sec<0){window.location='Login.aspx';}else{document.getElementById("span").innerHTML=sec;sec--;}},1000);</script>");
                Response.End();
            }
        }

    Web.BAL

    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Web.BAL
    {
        public class SQLAction
        {
            private SqlHelper helper = null;
            public SQLAction()
            {
                helper = new SqlHelper();
            }
    
            private Web.Model.Users users = null;
            //重点:
            //      关联表的对象就不能在这里置null了,
            //private Web.Model.Score score = null;
    
            private Dictionary<Web.Model.Users, Web.Model.Score> dUS = null;
            private List<Web.Model.Users> lsUsers = null;
    
            public bool IsExist(string number, string pwd)
            {
                return this.GetUser(number, pwd) != null;
            }
    
            public Web.Model.Users GetUser(string number, string pwd)
            {
                string sql = "select * from tblUsers where  u_Number=@num and u_Pwd=@pwd";
                SqlParameter[] param = { new SqlParameter("@num", number), new SqlParameter("@pwd", pwd) };
                using (SqlDataReader reader = helper.ExecuteDataReader(sql, param))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            users = new Model.Users();
                            users.ID = reader.GetInt32(0);
                            users.Name = reader.GetString(1);
                            users.Pwd = reader.GetString(2);
                            users.Num = reader.GetString(3);
                            // users.Number = this.GetScore(number);
                            //耗能。
                            //Web.Model.Users.Number = this.GetScore(number);
                            users.sNUM = this.GetScore(number);
                            users.Access = (bool?)reader.GetBoolean(4);
                            Web.Model.Users.USER = users;
                        }
                    }
                }
                return users;
            }
            private Web.Model.Score GetScore(string number)
            {
                 Web.Model.Score score = null;
                string sql = "select * from TblScore where s_Number=@num";
                //此时还能调用reader? 答案:YES
                using (SqlDataReader reader = helper.ExecuteDataReader(sql, new SqlParameter("@num", number)))
                {
                    if (reader.HasRows)
                    {
                        score = new Model.Score();
                        while (reader.Read())
                        {
                            score.ID = reader.GetInt32(0);
                            score.Number = reader.GetString(1);
                            score.CSharp = reader.IsDBNull(2) ? null : (int?)reader.GetInt32(2);
                            score.SQL = reader.IsDBNull(3) ? null : (int?)reader.GetInt32(3);
                            score.ASPNET = reader.IsDBNull(4) ? null : (int?)reader.GetInt32(4);
                        }
                    }
                }
                return score;
            }
            /// <summary>
            /// 这个走极端了
            /// </summary>
            /// <returns></returns>
            public Dictionary<Web.Model.Users, Web.Model.Score> GetUsersAndScore()
            {
                string sql = "select * from tblUsers";
                System.Data.DataTable dt = helper.ExecuteDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    dUS = new Dictionary<Web.Model.Users, Web.Model.Score>();
                    foreach (System.Data.DataRow item in dt.Rows)
                    {
                        users = new Web.Model.Users();
                        //根据数据库设计这里不判断IsNull了。
                        users.ID = int.Parse(item[0].ToString());
                        users.Name = item[1].ToString();
                        users.Pwd = item[2].ToString();
                        //users.Num = item[3].ToString();
                        //看看item[4]是什么 数字--boolean
                        users.Access = bool.Parse(item[4].ToString());
                        //添加value值为null是什么情况?
                        //key相同不相同
                        dUS.Add(users, this.GetScore(item[3].ToString()));
                    }
                }
                return dUS;
            }
            // 这样移植性大大降低了。
            // public List<Web.Model.Users> GetUsers(Dictionary<int, Web.Model.Users> dUS)
            public List<Web.Model.Users> GetUsers()
            {
                string sql = "select * from tblUsers";
                System.Data.DataTable dt = helper.ExecuteDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    lsUsers = new List<Web.Model.Users>();
                    foreach (System.Data.DataRow item in dt.Rows)
                    {
                        users = new Web.Model.Users();
                        //根据数据库设计这里不判断IsNull了。
                        users.ID = int.Parse(item[0].ToString());
                        users.Name = item[1].ToString();
                        users.Pwd = item[2].ToString();
                        users.Num = item[3].ToString();
                        users.sNUM = this.GetScore(item[3].ToString());
                        //看看item[4]是什么 数字--boolean:答案布尔
                        users.Access = bool.Parse(item[4].ToString());
                        lsUsers.Add(users);
                        //dUS.Add(users.ID, users);
                    }
                }
                return lsUsers;
            }
    
            public int Add(params string[] param)
            {
                //Add(name, pwd, num, access, csharp, sql, aspnet);
                string sqlU = "insert into tblUsers values(@name,@pwd,@num,@access)";
                SqlParameter[] paramU = { new SqlParameter("@name", param.GetValue(0)), new SqlParameter("@pwd", param[1]), new SqlParameter("@num", param.ElementAt(2)), new SqlParameter("@access", param[3]) };
                int tmp = helper.ExecuteNonQuery(sqlU, paramU);
                //
                if (param.Length > 4)
                {
                    string sqlS = "insert into TblScore values(@num,@csharp,@sql,@aspnet)";
                    SqlParameter[] paramS = { new SqlParameter("@num", param[2]), new SqlParameter("@csharp", param[4] == "" ? DBNull.Value : (object)param[4]), new SqlParameter("@sql", param[5] == "" ? DBNull.Value : (object)param[5]), new SqlParameter("@aspnet", param[6] == "" ? DBNull.Value : (object)param[6]) };
                    if (tmp == helper.ExecuteNonQuery(sqlS, paramS))
                        return 1;
                    return 0;
                }
                return tmp;
            }
            public int Del(string id)
            {
                string sql = "delete from tblUsers where u_ID=@id";
                return helper.ExecuteNonQuery(sql, new SqlParameter("@id", int.Parse(id)));
            }
    
            public int Modify<T>(T obj)
            {
                string sql = string.Empty;
                SqlParameter[] param = null;
                if (obj is Web.Model.Users)
                {
                    bool? acc = (obj as Web.Model.Users).Access;
                    sql = "update  tblUsers set u_Name=@name,u_Pwd=@pwd,u_Number=@num,u_Access=@access where u_ID=@id";
                    param = new SqlParameter[] {
                        new SqlParameter("@name",((Web.Model.Users)Convert.ChangeType(obj,typeof(Web.Model.Users))).Name),
                        new SqlParameter("@pwd",(obj as Web.Model.Users).Pwd),
                        new SqlParameter("@num",(obj as Web.Model.Users).Num),
                        //null 说明:管理员的修改,
                        new SqlParameter("@access",(acc==null?1:(acc==false?0:1))),
                        new SqlParameter("@id",(obj as Web.Model.Users).ID)
                            };
                }
                else
                {
                    sql = "update  tblScore set s_C#=@cs,s_SQL=@sql,s_ASPNET=@aspnet where s_ID=@id";
                    int? cs = (obj as Web.Model.Score).CSharp;
                    int? SQL = (obj as Web.Model.Score).SQL;
                    int? asp = (obj as Web.Model.Score).ASPNET;
                    param = new SqlParameter[] { new SqlParameter("@cs", cs == null ? DBNull.Value : (object)cs) ,
                    new SqlParameter("@sql",SQL==null?DBNull.Value:(object)SQL),
                    new SqlParameter("@aspnet",asp==null?DBNull.Value:(object)asp),
                    new SqlParameter("@id",(obj as Web.Model.Score).ID)};
                }
    
                return helper.ExecuteNonQuery(sql, param);
            }
        }
    }

    Web.Model

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Web.Model
    {
        public class Users
        {
            public Users()
            {
    
            }
            /// <summary>
            /// 当前登录者
            /// </summary>
            public static Users USER { get; set; }
    
            private int id;
            /// <summary>
            /// ID
            /// </summary>
            public int ID
            {
                get { return id; }
                set { id = value; }
            }
            private string name;
            /// <summary>
            /// Name
            /// </summary>
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            private string pwd;
            /// <summary>
            /// pwd
            /// </summary>
            public string Pwd
            {
                get { return pwd; }
                set { pwd = value; }
            }
            private string num;
            /// <summary>
            /// number
            /// </summary>
            public string Num
            {
                get { return num; }
                set { num = value; }
            }
            
            //private static Score number;
            ///// <summary>
            ///// 当前登录者Score--number
            ///// </summary>
            //public static Score Number
            //{
            //    get { return number; }
            //    set { number = value; }
            //}
            private Score sNum;
            /// <summary>
            /// Score--Number
            /// </summary>
            public Score sNUM
            {
                get { return sNum; }
                set { sNum = value; }
            }
            
            private bool? access;
            /// <summary>
            /// access
            /// </summary>
            public bool? Access
            {
                get { return access; }
                set { access = value; }
            }
    
        }
        public class Score
        {
            public Score()
            {
    
            }
            private int id;
            /// <summary>
            /// id
            /// </summary>
            public int ID
            {
                get { return id; }
                set { id = value; }
            }
            private string number;
            /// <summary>
            /// number  
            /// </summary>
            public string Number
            {
                get { return number; }
                set { number = value; }
            }
            private int? csharp;
            /// <summary>
            /// C#
            /// </summary>
            public int? CSharp
            {
                get { return csharp; }
                set { csharp = value; }
            }
            private int? sql;
            /// <summary>
            /// sql
            /// </summary>
            public int? SQL
            {
                get { return sql; }
                set { sql = value; }
            }
            private int? aspnet;
            /// <summary>
            /// aspnet
            /// </summary>
            public int? ASPNET
            {
                get { return aspnet; }
                set { aspnet = value; }
            }
    
        }
    }

    项目文件:http://pan.baidu.com/s/1dDf5mlb

  • 相关阅读:
    方法参数个数最多不宜超过4个
    避免方法中使用大量局部变量
    JQuery学习备忘
    CSS学习备忘
    解析Path方法备忘
    获取差集合的一种实现思路
    前台JSP页面独立化
    requireJs的使用
    handlebar
    移动端h5<a>标签点击样式去除
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/3663150.html
Copyright © 2011-2022 走看看