1. 程式人生 > >BS(三層)—增刪改查——Web窗體(aspx)版本

BS(三層)—增刪改查——Web窗體(aspx)版本

   上一篇我們用一般處理程式寫了(ashx)寫了一遍增刪改查,今天我們將用Web窗體(aspx)寫一遍增刪改查。我們平時寫的時候到底用一般處理程式呢?還是用Web窗體呢?

    簡單來說web窗體(aspx)是一般處理程式(ashx)的一個複雜版本。一般處理程式需要呼叫一個靜態的Html頁面,當HTML佈局特別複雜的時候,這時候一般處理程式將會寫起來很麻煩,開發效率太低。於是出現了Web窗體。當我們建一個Web窗體的時候,會自動生成一個WebForm.aspx.cs這樣的一個類。它相當於Web窗體Form1.aspx的父類。

 我們先來欣賞一下WebForm1.aspx介面

 如果在WebForm1.aspx介面寫C#程式碼必須在<% %>裡面

  Inherits表示繼承:WebForm.aspx.cs類,它相當於Web窗體Form1.aspx類的父類。

  CodeBehind:表示後置程式碼要在WebForm.aspx.cs裡面寫。

 總結一點:複雜的頁面佈置用web窗體,簡單的用一般處理程式 

一、查

    第一種寫法

WebForm1.aspx頁面程式碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebUI2.WebForm1" %>

<!DOCTYPE html>
<%@ Import  Namespace="Model" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="CSS/tableStyle.css" rel="stylesheet" />
    <script  type="text/javascript">
        window.onload = function () {
          var datas = document.getElementsByClassName("deletes");
            var dataLength = datas.length;
            for (var i = 0; i < dataLength; i++) {  
                datas[i].onclick = function () {
                    if (!confirm("確定要刪除嗎?")) {
                        return false; 
                    }
                }
            }
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <a href="Adduser.aspx">新增使用者</a>
            <table>
        <tr>
            <th>編號</th>
            <th>使用者名稱</th>
            <th>密碼</th>
            <th>郵箱</th>
            <th>時間</th>
            <th>刪除</th>
            <th>詳細</th>
            <th>編輯</th>
        </tr>    
             <%--<% =StrHtml %>--%>
                <% foreach (userInfo user in userList)
                    {%>
                        <tr>    
                            <td><%=user.Id %></td>
                            <td><%=user.userName %></td>
                            <td><%=user.userPass %></td>
                            <td><%=user.Email %></td>
                            <td><%=user.regTime.ToShortDateString()%></td>
                            <td><a href="Del.ashx?id=<%=user.Id %>"class="deletes">刪除</a></td>
                            <td> 詳細</td>
                            <td>  <a href="UpdateUser.aspx?id=<%=user.Id %>">編輯</a></td>
                        </tr>
                    <%} %> 
                       
    </table>
        </div>
    </form>
</body>
</html>
 

WebForm.aspx.cs頁面程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
namespace WebUI2
{
    public partial class WebForm1 : System.Web.UI.Page
    {   
        public List<userInfo> userList { get; set; }
        /// <summary>
        /// 頁面載入完成以後執行Load事件,aspx介面相當於父類
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
             userInfoBLL bll = new userInfoBLL();
            //接收返回來的資料
            List<userInfo> list = bll.GetList();
            userList = list;           
        }
    }
}

第二種寫法:

WebForm1.aspx頁面程式碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebUI2.WebForm1" %>

<!DOCTYPE html>
<%@ Import  Namespace="Model" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="CSS/tableStyle.css" rel="stylesheet" />
    <script  type="text/javascript">
        window.onload = function () {
          var datas = document.getElementsByClassName("deletes");
            var dataLength = datas.length;
            for (var i = 0; i < dataLength; i++) {  
                datas[i].onclick = function () {
                    if (!confirm("確定要刪除嗎?")) {
                        return false; 
                    }
                }
            }
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <a href="Adduser.aspx">新增使用者</a>
            <table>
        <tr>
            <th>編號</th>
            <th>使用者名稱</th>
            <th>密碼</th>
            <th>郵箱</th>
            <th>時間</th>
            <th>刪除</th>
            <th>詳細</th>
            <th>編輯</th>
        </tr>    
             <% =StrHtml %>
                
    </table>
        </div>
    </form>
</body>
</html>
 

WebForm.aspx.cs頁面程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
namespace WebUI2
{
    public partial class WebForm1 : System.Web.UI.Page
    {   public string StrHtml { get; set; }
        
        /// <summary>
        /// 頁面載入完成以後執行Load事件,aspx介面相當於父類
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
             userInfoBLL bll = new userInfoBLL();
            //接收返回來的資料
            List<userInfo> list = bll.GetList();
            //userList = list;
            StringBuilder sb = new StringBuilder();
            //遍歷實體資訊
            foreach (userInfo user in list)
            {
                sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><a href='DeleteUser.ashx?id={0}'class='deletes'>刪除</a></tr>"
                , user.Id, user.userName, user.userPass, user.Email, user.regTime.ToShortDateString());
            }
            //將遍歷結果給StrHtml
            StrHtml = sb.ToString();
        }
    }
}

二、增

AddUser.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddUser.aspx.cs" Inherits="WebUI2.AddUser" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        使用者名稱:<input type="text" name="txtName"/><br />
        密碼:<input type="password" name="txtPwd"/><br />
        郵箱:<input type="text" name="txtMail"/><br />         
        <input type="submit" value="新增" />
        </div>
    </form>
</body>
</html>

AddUser.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
namespace WebUI2
{
    public partial class AddUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //如果隱藏域的值不為空,表示使用者單擊了提交按鈕,發出了POST請求
            if(IsPostBack)
            {
                InsertUser();
            }
        }
        protected void InsertUser() 
        {
            userInfo user=new userInfo();
            user.userName = Request.Form["txtName"];
            user.userPass = Request.Form["txtPwd"];
            user.Email = Request.Form["txtMail"];
            user.regTime = DateTime.Now;
            userInfoBLL bll = new userInfoBLL();
            if(bll.AddUserInfo(user))
            {
                Response.Redirect("WebForm1.aspx");
            }
            else 
            {
                Response.Redirect("Error.html");
            }
            
        }
    }
}

刪:一般處理程式(ashx)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BLL;
using Model;
namespace WebUI2
{
    /// <summary>
    /// Del 的摘要說明
    /// </summary>
    public class Del : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int id;
            if (int.TryParse(context.Request.QueryString["id"], out id))
            {
                userInfoBLL Bll = new userInfoBLL();
                if (Bll.DeleteUserInfo(id))
                {
                    //刪除成功後返回到handerUserinfo.ashx介面,重新資料庫資料
                    context.Response.Redirect("WebForm1.aspx");
                }
                else
                {
                    context.Response.Redirect("Error.html");
                }
            }
            else
            {
                context.Response.Write("引數錯誤");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

改:

UpdateUser.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpdateUser.aspx.cs" Inherits="WebUI2.UpdateUser" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
             使用者名稱:<input type="text" name="txtName"value="<%=EditUser.userName %>"/><br />
             密碼:<input type="password" name="txtPwd"value="<%=EditUser.userPass %>"/><br />
             郵箱:<input type="text" name="txtMail"value="<%=EditUser.Email %>"/><br /> 
            <input type="hidden" name="txtId" value="<%=EditUser.Id %>" />
            <input type="hidden" name="txtRegtime" value="<%=EditUser.regTime %>" />
            <input type="submit" value="修改" />
        </div>
    </form>
</body>
</html>

UpdateUser.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
namespace WebUI2
{
    public partial class UpdateUser : System.Web.UI.Page
    {
        public userInfo EditUser { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Update();
            }
            else
            {
                ReadyUpdate();
            }
           
        }
        //對資料進行更新
        protected void ReadyUpdate()
        {
            userInfo user = new userInfo();
            user.Id = Convert.ToInt32(Request.Form["txtId"]);
            user.userName = Request.Form["txtName"];
            user.userPass = Request.Form["txtPwd"];
            user.Email = Request.Form["txtMail"];
            user.regTime = Convert.ToDateTime(Request.Form["txtRegtime"]);
            userInfoBLL bll = new userInfoBLL();
            if (bll.UpdateUser(user))
            {
                Response.Redirect("WebForm1.aspx");
            } 
            else
            {
                Response.Redirect("Error.html");
            }
        }
        //獲取使用者的資料
        public void Update()
        {   
            int id;
            if (int.TryParse(Request.QueryString["id"], out id))
            {
                userInfoBLL Bll = new userInfoBLL();
                userInfo user = Bll.GetUserInfo(id);
                if (user!=null){
                    EditUser = user;
                }
                else
                {
                    Response.Write("Error.html");
                }                            
            }
            else
            {
                Response.Write("Error.html");
            }
        }
    }
}

Error.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>   
    <script type="text/javascript">
      window.onload =function() {
          setTimeout(change,1000);
        }
        function change() {
            var time = document.getElementById("time").innerHTML;
            time = parseInt(time);
            time--;
            if (time < 1) {
                window.Location.href = "HanderUserInfo.ashx"
            }
            else {
                document.getElementById("time").innerHTML = time;
                setTimeout(change, 1000)
            }
        }     
    </script>
</head>
<body>
    伺服器忙!<span style="font-size:20px;color:red "id="time">5</span>秒鐘後自動跳轉<a href="HanderUserInfo.ashx">使用者列表</a>
</body>
</html>

效果展示:

重點學習:

    例如當執行修改功能的時候,我們對同一個webForm1.aspx請求了兩次,第一次將修改的人的資訊賦值到文字框中,第二次,修改完使用者資料以後,再次請求了webForm1.aspx。第一次請求無非獲取使用者資訊,用的是Get請求,修改完成資訊以後,我們用的是Post請求。對同一個網址我們連續訪問兩次,兩次需要的結果是不同的,我們需要判斷是什麼請求,這裡用到了IsPostBack。

IsPostBack:

   如果Post請求該屬性值為true,如果Get請求該屬性值為False. 它會根據__VIEWSTATE隱藏域進行判斷,如果為post請求,該隱藏域的值會提交到服務端,那麼ISpostBack的屬性為True。

注意:

      如果用ISPostBack判斷是Get請求還是Post 請求,Form標籤一定是runat="server"

      如果去掉form標籤裡面的runat="server"將不會產生__VIEWSTATE

 今天的分享就先到這合理,如果本篇部落格對您有所幫助,記得點贊哦!