上午对asp.net三层架构有了一个比较清晰的认识,并且做了一个简单的登录案例.

asp.net三层架构初探<一>

下午用三层做了一个比较简单的新闻管理系统

我们先看一下系统需求:

asp.net三层架构初探<二>_edn

相信大家一看便知:

ok接下来就可以直接上代码啦!当然写代码的循序还是和前一篇博文一样

先说一下,因为我的布局太差了,所有没有任何的样式

<1>modle层

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Model
 7 {
 8     public class MDataOperation
 9     {
10         private int _id;
11         private string _title;
12         private string _content;
13         
14         public int id
15         {
16             set{_id=value;}
17             get{return _id;}
18           
19         }
20         public string title
21         {
22             set { _title = value; }
23             get { return _title; }
24         }
25         public string content
26         {
27             set { _content = value; }
28             get { return _content; }
29         }
30 
31         public MDataOperation() { }  //空的类的构造函数
32 
33     }
34 }

<2>DAL
SqlHelper类

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data.SqlClient;
  6 using System.Data;
  7 using System.Data.Common;
  8 
  9 namespace DAL
 10 {
 11     class SqlHelper
 12     {
 13         /// <summary>
 14         /// 返回数据连接字符串connString
 15         /// </summary>
 16         /// <returns></returns>
 17       public string GetConnectionString()
 18       {
 19           string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
 20           return connString;
 21       }
 22 
 23         /// <summary>
 24         /// 返回dataset数据
 25         /// </summary>
 26         /// <param name="sql"></param>
 27         /// <returns></returns>
 28       public DataSet GetDataSet(string sql)
 29       {
 30           //得到数据库连接
 31           SqlConnection conn = new SqlConnection(GetConnectionString());
 32           //打开连接
 33           conn.Open();
 34 
 35           DataSet ds = new DataSet();
 36           SqlDataAdapter da = new SqlDataAdapter(sql, conn);
 37           da.Fill(ds);
 38 
 39           //关闭连接
 40           conn.Close();
 41 
 42           return ds;
 43       }
 44 
 45         /// <summary>
 46         /// 返回选中的一行数据
 47         /// </summary>
 48         /// <param name="id"></param>
 49         /// <returns></returns>
 50         public DataRow GetCheckedNews(int id)
 51       {
 52           //得到数据库连接
 53           SqlConnection conn = new SqlConnection(GetConnectionString());
 54           DataSet ds = new DataSet();
 55            //打开连接
 56           conn.Open();
 57 
 58           string sql = "select * from News where id=@id";
 59           sql = sql.Replace("@id",id.ToString());
 60        
 61           SqlDataAdapter da = new SqlDataAdapter(sql, conn);
 62           da.Fill(ds);
 63 
 64           DataRow row = ds.Tables[0].Rows[0];
 65 
 66           
 67           ds.Dispose();
 68          //关闭连接
 69           conn.Close();
 70           //返回选中的行
 71           return row;
 72         
 73       }
 74 
 75         /// <summary>
 76         /// 执行sql操作(内容根据sql而定,可以是删除,插入,等返回操作是否成功的bool值)
 77         /// </summary>
 78         /// <param name="id"></param>
 79         /// <returns></returns>
 80         public bool SqlExecuteNonQuery(string sql)
 81         {
 82             //得到数据库连接
 83             SqlConnection conn = new SqlConnection(GetConnectionString());
 84             //打开连接
 85             conn.Open();
 86 
 87             //定义一个事物
 88            // SqlTransaction trans;
 89             SqlCommand cmd = new SqlCommand(sql, conn);
 90             //将cmd该操作赋值给事物
 91             //trans = cmd.Transaction;
 92 
 93             try
 94             {
 95                 //执行操作,提交事物
 96                 cmd.ExecuteNonQuery();
 97                // trans.Commit();
 98                 return true;
 99             }
100             catch
101             {
102                 //事物回滚
103                // trans.Rollback();
104                 return false;
105             }
106             finally
107             {
108                 //关闭连接
109                 conn.Close();
110             }
111 
112            
113 
114         }
115 
116     }
117 }

DAL类

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using Model;
 7 
 8 
 9 namespace DAL
10 {
11      public class DDataOperation
12     {
13          //调用SqlHelper类
14          SqlHelper sqlHelp = new SqlHelper();
15       
16 
17          /// <summary>
18          /// 显示所有或符合局部条件的news,返回dataset
19          /// </summary>
20          /// <param name="sql"></param>
21          /// <returns></returns>
22          public DataSet GetDataSetOfNewsList(string sql)
23          {
24              DataSet ds = new DataSet();
25              ds = sqlHelp.GetDataSet(sql);
26              return ds;
27          }
28 
29 
30          /// <summary>
31          /// 返回选中的一行数据
32          /// </summary>
33          /// <param name="id"></param>
34          /// <returns></returns>
35          public DataRow GetCheckedNews(MDataOperation operation)
36          {
37              int id = operation.id;
38              DataRow row = sqlHelp.GetCheckedNews(id);
39              return row;
40          }
41 
42 
43          /// <summary>
44          /// 执行操作(删除,插入等,返回bool值)
45          /// </summary>
46          /// <param name="sql"></param>
47          /// <returns></returns>
48          public bool Operation(Model.MDataOperation Mnews)
49          {
50              string sql = "insert into News values('@name','@content','1','@daytime')";
51              sql = sql.Replace("@name",Mnews.title);
52              sql = sql.Replace("@content",Mnews.content);
53              sql = sql.Replace("@daytime",DateTime.Now.ToString());
54              return sqlHelp.SqlExecuteNonQuery(sql);
55          
56          }
57 
58     }
59 }

<3>BLL层

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using Model;
 7 using DAL;
 8 
 9 
10 namespace BLL
11 {
12     public class BDataOperation
13     {
14         DAL.DDataOperation dataOperation = new DAL.DDataOperation();
15         Model.MDataOperation MdataOperations = new Model.MDataOperation();
16         
17 
18         /// <summary>
19         /// 调用返回dataset
20         /// </summary>
21         /// <param name="sql"></param>
22         /// <returns></returns>
23         public DataSet GetDataSet(string sql)
24         {
25             DataSet ds = new DataSet();
26             ds = dataOperation.GetDataSetOfNewsList(sql);
27             return ds; 
28         }
29 
30         /// <summary>
31         /// 返回选中的一行数据
32         /// </summary>
33         /// <returns></returns>
34         public DataRow GetCheckedNews(int id)
35         {
36             MdataOperations.id = id;
37             DataRow row = dataOperation.GetCheckedNews(MdataOperations);
38             return row;
39 
40         }
41 
42         /// <summary>
43         /// 执行操作添加新闻
44         /// </summary>
45         /// <param name="sql"></param>
46         /// <returns></returns>
47         public bool Operation(string title,string content)
48         {
49             MdataOperations.title = title;
50             MdataOperations.content = content;
51 
52             bool ok=dataOperation.Operation(MdataOperations);
53             return ok;
54             
55         }
56 
57     }
58 }

<4>Web层
Defult.aspx

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 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 </head>
 8 <body>
 9     <form id="form1" runat="server">
10     <div>
11         <asp:Repeater ID="Repeater1" runat="server" >
12             <HeaderTemplate>
13                 <table width="900px">
14                     <tr>
15                         <td >
16                             编号
17                         </td>
18                         <td>
19                             题目
20                         </td>
21                         <td>

22                             内容简介
23                         </td>
24                         <td>
25                             状态
26                         </td>
27                         <td>
28                             上传时间
29                         </td>
30                         <td>
31                            查看
32                         </td>
33                     </tr>
34             </HeaderTemplate>
35             <ItemTemplate>
36                 <tr>
37                     <td >
38                         <%#Eval("id")%>
39                     </td>
40                     <td>
41                         <%#Eval("name")%>
42                     </td>
43                     <td>
44                         <%#Eval("content")%>
45                     </td>
46                     <td>
47                         <%#Eval("state")%>
48                     </td>
49                     <td>
50                         <%#Eval("day")%>
51                     </td>
52                     <td>
53                    <asp:HyperLink ID="HyperLink1" NavigateUrl='<%#"Detail.aspx?id="+DataBinder.Eval(Container.DataItem,"id") %>' runat="server">详情</asp:HyperLink>
54                      
55                    
56                     </td>
57                 </tr>
58             </ItemTemplate>
59             <FooterTemplate>
60                 </table>
61             </FooterTemplate>
62         </asp:Repeater>
63     </div>
64     <br /><br /><br /><br />
65     <div runat="server"  id="addNews">
66        文章标题: <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox><br />
67        内容:<asp:TextBox ID="txtContent" TextMode="MultiLine"  Width="500px" Height="50px" runat="server"></asp:TextBox><br />
68         <asp:Button ID="AddNewsBtn" runat="server" Text="提交" onclick="AddNewsBtn_Click" />
69     </div>
70     </form>
71 </body>
72 </html>

Defult.aspx.cs

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 using System;
 2 using System.Configuration;
 3 using System.Data;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Security;
 7 using System.Web.UI;
 8 using System.Web.UI.HtmlControls;
 9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12 
13 
14 public partial class _Default : System.Web.UI.Page
15 {
16     BLL.BDataOperation operation = new BLL.BDataOperation();
17 
18     protected void Page_Load(object sender, EventArgs e)
19     {
20         ShowNewsList();
21     }
22 
23     protected void ShowNewsList()
24     {
25         DataSet ds = operation.GetDataSet("select * from News ");
26         Repeater1.DataSource = ds;
27         Repeater1.DataBind();
28 
29     }
30 
31     protected void AddNewsBtn_Click(object sender, EventArgs e)
32     {
33         bool boolOk=  operation.Operation(txtTitle.Text,txtContent.Text);
34         if (boolOk == true)
35         {
36             Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript'>alert('添加成功')</script>");
37         }
38         else
39         {
40             Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript'>alert('添加失败')</script>");
41             Response.AddHeader("refresh","0");
42         }
43     }
44 }

Detail.aspx

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detail.aspx.cs" Inherits="Detail" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <title>无标题页</title>
 8 </head>
 9 <body>
10     <form id="form1" runat="server">
11     <div>
12     标题:<asp:Label ID="title" runat="server" Text="Label"></asp:Label>
13     详细内容:
14         <asp:Label ID="content" runat="server" Text="Label"></asp:Label>
15     </div>
16     </form>
17 </body>
18 </html>

Detail.aspx.cs

asp.net三层架构初探<二>_edn_02asp.net三层架构初探<二>_taro_03View Code
 1 using System;
 2 using System.Collections;
 3 using System.Configuration;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Security;
 8 using System.Web.UI;
 9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using BLL;
14 
15 public partial class Detail : System.Web.UI.Page
16 {
17     BLL.BDataOperation operation = new BDataOperation();
18     Model.MDataOperation Moperation = new Model.MDataOperation();
19 
20     protected void Page_Load(object sender, EventArgs e)
21     {
22         ShowCheckedNews();
23     }
24     public void ShowCheckedNews()
25     {
26         int id = int.Parse(Request.QueryString["id"].ToString());
27         DataRow row = operation.GetCheckedNews(id);
28 
29         title.Text = row["name"].ToString();
30         content.Text = row["content"].ToString();
31     }
32 
33 
34 }

 以上完毕!!

相信大家有点迷惑!!和我一样,上午我还在想,三层能用来干嘛,一个小项目要是用三层的话,这层折腾折腾,那层折腾,超麻烦!

写到这里我终于明白了:

1;三层适合大项目

2:由于三层之间独立,后期修改比较方便

3:有没有看到cs文件,明显代码少了很多,只是调用一下BLL中的方法!

举个例子:当你添加新闻时:

cs文件AddNewsBtn_Click(object sender, EventArgs e)调用operation.Operation(txtTitle.Text,txtContent.Text)

→ BLL层:Operation(string title,string content)(将title,content放入数据对象MdataOperations中)调用dataOperation.Operation(MdataOperations)

→ DAL层:Operation(Model.MDataOperation Mnews) 再调用sqlhelper将数据插入数据库

从这里我们可以看出:

step1:cs文件只是调用BLL中的方法 ,并传参数到BLL层

step2:BLL层将数据封装成modle层的数据对象,将该对象传递给BLL层

step3:调用内部方法处理数据,并一层一层的返回结果

这就是一次业务请求的数据命令流程