1. 程式人生 > >(轉)ASP.NET實現三層架構網站建立流程

(轉)ASP.NET實現三層架構網站建立流程

1.新建專案—>Visual C#—>Web—>ASP.NET空Web應用程式  或者  新建網站—>ASP.NET空網站

2.在解決方案處右擊—>新建專案—>Windows—>類庫,分別建立三層架構,Model(實體層)、Dll(邏輯層)、DAL(資料層),在每一層中建立如下圖。

3.建立好三層類庫後,在Model類庫專案上右擊,選擇新增—>類,並命名,如下圖。

4.在建立好類之後(每一個類對應資料庫中的一個表),輸入private string Sname(string是資料庫中欄位型別,Sname是資料庫中欄位名,與自己的資料庫表相對應),如何對private string Sname選中—>右擊—>選擇重構—>封裝欄位,然後點選確定即可,實現了對資料庫中表的一個欄位進行封裝,其餘欄位封裝步驟跟上述一樣,在建立完之後點選工具欄處的“生成”—>生成Model即可。操作步驟如下圖,我的封裝後的程式碼如下(根據自己的資料庫表進行封裝)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Model
{
    public class Users
    {
        private string Sname;//欄位型別和欄位名要與資料庫對應
 
        public string Sname1//封裝後的欄位
        {
            get { return Sname; }
            set { Sname = value; }
        }
 
        private string Ssex;
 
        public string Ssex1
        {
            get { return Ssex; }
            set { Ssex = value; }
        }
 
        private string Snumber;
 
        public string Snumber1
        {
            get { return Snumber; }
            set { Snumber = value; }
        }
 
        private string Sgrade;
 
        public string Sgrade1
        {
            get { return Sgrade; }
            set { Sgrade = value; }
        }
 
        private string Steacher;
 
        public string Steacher1
        {
            get { return Steacher; }
            set { Steacher = value; }
        }
 
        private string Sid;
 
        public string Sid1
        {
            get { return Sid; }
            set { Sid = value; }
        }
 
    }
}

5.對DAL層進行程式碼的編寫,主要分為:(1)資料庫連線函式,(2)執行sql語句函式,(3)sql語句書寫和相應引數儲存函式,注意:要在檔案頭部引用using System.Data; using System.Data.SqlClient; using Model; 前兩個是asp.net整合的資料庫操作庫,呼叫其中相關函式、變數即可,最後一個是我們自己建立的Model類(在使用using Model命令之前需要將Model這個類在DAL這個專案中引用,在DAL專案中的“引用”處右擊,選擇新增引用,選擇專案找到Model這個專案類確定即可)。其中sql語句執行函式根據返回型別不同有多種,自己可查相關資料學習,sql語句中相應欄位實參的儲存、傳遞方法也多種,自己可查相關資料學習,我的DAL程式碼如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Model;
 
namespace DAL
{
    public class UserService
    {
 
        //連線資料庫
        public static SqlConnection connection;
        public static SqlConnection Connection
        {
            get
            {
                if (connection == null)
                {
                    //遠端連線資料庫命令(前提遠端資料庫伺服器已經配置好允許遠端連線)
                    string strConn = @"Data Source=172.18.72.158;Initial Catalog=WebKuangjia;User ID=sa;Password=LIwei123;Persist Security Info=True";
 
                    //連線本地資料庫命令
                    //string strConn = @"Data Source=.;Initial Catalog=WebKuangjia;Integrated Security=True";
 
                    connection = new SqlConnection(strConn);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
                return connection;
            }
        }
 
        //執行sql語句,返回被修改行數
        public static int ExecuteCommand(string commandText, CommandType commandType, SqlParameter[] para)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Connection;
            cmd.CommandText = commandText;
            try
            {
                if (para != null)
                {
                    cmd.Parameters.AddRange(para);
                }
                return cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }
 
        //執行sql語句,返回資料庫表
        public static DataTable GetDataTable(string commandText, CommandType commandType, SqlParameter[] para)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = Connection;
            cmd.CommandText = commandText;
            cmd.CommandType = commandType;
            try
            {
                if (para != null)
                {
                    cmd.Parameters.AddRange(para);
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable temp = new DataTable();
                da.Fill(temp);
                return temp;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }
 
        //增加使用者
        public static bool AddStudent(Users user)
        {
            string sql = "insert into Student(Sname,Ssex,Snumber,Sgrade,Steacher)" + "values(@name,@sex,@number,@grade,@teacher)";//sql語句字串
            if (user.Ssex1==null)
            {
                user.Ssex1 = "";
            }
            if (user.Sgrade1 == null)
            {
                user.Sgrade1= "";
            }
            if (user.Steacher1 == null)
            {
                user.Steacher1 = "";
            }
            SqlParameter[] para = new SqlParameter[]//儲存相應引數的容器
            {
                new SqlParameter("@name",user.Sname1),
                new SqlParameter("@sex",user.Ssex1),
                new SqlParameter("@number",user.Snumber1),
                new SqlParameter("@grade",user.Sgrade1),
                new SqlParameter("@teacher",user.Steacher1),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);//呼叫執行sql語句函式
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }
 
        }
 
        //查詢資料庫表
        public static DataTable Selecttable()
        {
            string sql = "select * from Student";
            return GetDataTable(sql, CommandType.Text, null);
        }
 
        //刪除使用者
        /****************刪除使用者返回影響行數*****************/
        public static bool DeleteStudentBySnumber(string number)
        {
            string sql = "delete from Student where [email protected]";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@number",number),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /****************刪除使用者返回表*****************/
        public static DataTable DeleteStudentBySid(int id)
        {
            string sql = "delete from Student where [email protected]";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@id",id),
            };
            return GetDataTable(sql, CommandType.Text, para);
        }
 
        //修改使用者
        public static bool ModifyStudent(Users user)
        {
            string sql = "update Student set [email protected],[email protected],[email protected],[email protected],[email protected] where [email protected]";
            SqlParameter[] para = new SqlParameter[]
             {
                new SqlParameter("@name",user.Sname1),
                new SqlParameter("@sex",user.Ssex1),
                new SqlParameter("@number",user.Snumber1),
                new SqlParameter("@grade",user.Sgrade1),
                new SqlParameter("@teacher",user.Steacher1),
                new SqlParameter("@id",user.Sid1),
             };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
        //查詢使用者
        public static bool QueryStudent(string number)
        {
            string sql = "select * from Student where [email protected]";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@number",number),
            };
            int count = ExecuteCommand(sql, CommandType.Text, para);
            if (count>0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

6.Dll層(邏輯層),只是一箇中間層,負責引數的傳遞和呼叫DAL中的函式,注意標頭檔案需要包含:using System.Data;using System.Data.SqlClient;using Model;using DAL;
將Model和DAL類進行包含(先引用這兩個類,引用方法在步驟五中已經介紹),Dll層每個函式的返回型別需要與DAL中相應函式的返回型別一致,我的Dll程式碼如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Model;
using DAL;
 
namespace Dll
{
    public class UserManage
    {
        public static bool add(Users user)
        {
            return UserService.AddStudent(user);
        }
        public static bool delete(string number)
        {
            return UserService.DeleteStudentBySnumber(number);
        }
        public static bool xiugai(string number)
        {
            return UserService.QueryStudent(number);
        }
        public static bool modify(Users user)
        {
            return UserService.ModifyStudent(user);
        }
        public static bool select(string number)
        {
            return UserService.QueryStudent(number);
        }
        public static DataTable table()
        {
            return UserService.Selecttable();
        }
        public static DataTable deletebyid(int id)
        {
            return UserService.DeleteStudentBySid(id);
        }
    }
}
 

7.在三層架構檔案建立成功之後,只需要在前臺引用Model和Dll即可,在using中新增using System.Data;using System.Data.SqlClient;using Model;using Dll;,剩餘的就是控制元件的使用了,我用的是gridview控制元件進行資料表的操作,關於gridview控制元件的詳細使用參考http://blog.csdn.net/21aspnet/article/details/1540301。我的前臺程式碼如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Model;
using Dll;
 
namespace WebKuangJia
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           if (!IsPostBack)//初次載入該頁
            {
                gvbind();
           }
 
        }
 
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string number = GridView1.Rows[e.RowIndex].Cells[3].Text;
            UserManage.delete(number);
           // GridView1.DataBind();
            gvbind();
        }
 
        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            GridView1.SelectedIndex = e.NewSelectedIndex;
            //GridView1.DataBind();
            gvbind();
        }
 
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
           GridView1.EditIndex = e.NewEditIndex;
           // GridView1.DataBind();
           gvbind();
        }
 
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Users us = new Users();
            us.Sid1 = GridView1.DataKeys[e.RowIndex].Value.ToString();//獲取編輯行的資料主鍵值//((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text;//[0].Controls[0]).Text;
            us.Sname1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString().Trim();//獲取編輯行的第1列的textbox控制元件中的內容賦值給Users物件us的Sname1封裝欄位
            us.Ssex1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString().Trim();
            us.Snumber1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString().Trim();
            us.Sgrade1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString().Trim();
            us.Steacher1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString().Trim();
            if (UserManage.modify(us))
            {
               GridView1.EditIndex = -1;
               //GridView1.DataBind();
               gvbind();
            }
            else
            {
                Response.Write("<script>alert('修改失敗!')</script>");
            }
 
        }
 
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
           // GridView1.DataBind();
            gvbind();
        }
 
        private void gvbind()
        {
            DataTable list;//宣告表變數
            list = UserManage.table();
            GridView1.DataSource = list;
            GridView1.DataKeyNames = new string[] { "Sid" };//主鍵
            GridView1.DataBind();
        }
    }
}

8.按照上述步驟即實現了網站的建立和資料的增刪改查操作,其餘網站的功能和上述型別,只需要新增相應的Model子類、Dll子類和DAL子類即可(所說的子類是在類庫專案中新增的類而已,並進行相應程式碼的書寫),我的資料庫表如下,前臺測試如下。

相關推薦

ASP.NET實現架構網站建立流程

1.新建專案—>Visual C#—>Web—>ASP.NET空Web應用程式  或者  新建網站—>ASP.NET空網站 2.在解決方案處右擊—>新建專案—>Windows—>類庫,分別建立三層架構,Model(實體層)、Dll(

ASP.NET實現架構網站建立流程

1.新建專案—>Visual C#—>Web—>ASP.NET空Web應用程式  或者  新建網站—>ASP.NET空網站 2.在解決方案處右擊—>新建專案—>Windows—>類庫,分別建立三層架構,Model(實體層)、Dll(

Asp.net mvc+架構註冊篇

                                            &

ASP.NET中常見文件類型及用途

bin 許可 程序集 授權 rac 查看 類關系 置配 執行 從入門導師那繼承來的習慣,也是加上自己的所謂經驗判斷,一直對WEB開發不太感冒,可惜呀,從業近二十年,還得從頭開始對付HTML、CSS、JS、ASPX,以前的經驗,用不上啦!!!先從好好學習ASPX開發入手吧!

ASP.NET MVC架構基礎詳細操作圖文教程(VS2017)(2)

沒錯,Userinformation_BLL.cs類就是邏輯類。我們先把DAL層的方法都COPY過來,因為他們是要是BLL層裡實現的,當然我是倒著講的,所以現在我們倒著在實現,嘿嘿。按理來說,我們應該先UI,再BLL,最後再DAL。為了方便大家深入了理解,所以我就反著來了。COPY過來後,我們刪掉方法內的內容

ASP.NET MVC架構基礎詳細操作圖文教程(VS2017)(3)

作者marker 歡迎轉載!!!講到這裡,我們已經把BLL和DAL都封裝好了。接下來的就只是呼叫。因為本文主要是講述的ASP.NET MVC的三層架構,所以從最底層的DAL到BLL到現在UI反著來的,如果是現實中的專案咱們就不能這麼做了。得先做需求,然後做設計,然後搭建框架針

ASP.NET MVC架構基礎詳細操作圖文教程(VS2017)(1)

 現在我們要對專案進行三層架構,剛才我們在建立專案的時候,已經建立了UI層,即web專案。現在我們要建立BLL層和DAL層等 。如下圖左側,我們選擇Visual C#專案,右則我們選擇類庫。然後在名稱中輸入StudyCSharp.BLL路徑地址可以不用更改。根據以上操作,我們再建立StudyCSharp.DA

17ASP.NET Core EF基於資料模型建立資料庫

1.簡介 使用Entity Framework Core構建執行基本資料訪問的ASP.NET Core MVC應用程式。使用遷移(Migrations)基於資料模型建立資料庫,你可以在Windows上使用Visual Studio 2017 PowerShell或在Windows、macOS或Linux上使

Asp.Net MVC+EF+架構 簡單搭建 1 Asp.Net MVC+EF+架構

首先,謝謝各位過客觀看,今天我們說下簡單的 Asp.Net MVC+EF+三層架構 搭建( 第一部分)。 很簡單,先看下完成之後程式碼圖:   這裡講的是一個整體框架的搭建,所以頁面暫時Pass,先以一個小的查詢為例。   一、新建Model、Dal、Bl

建設局專案總結——ASP.NET 實現自動捕獲異常和異常處理

               建設局專案幾乎要接近尾聲了,從頭到尾差不多有半個月的時間吧,半個月 不知不覺就這樣過去了,總結這半個月,好像每天都很忙,每天都很忙碌,但是仔細想想好像又沒做出多少正兒八經的工作量,總共做了下面幾個模組: 獎項懲罰列表,編輯等 企業資訊編輯

】SignalR新手系列教程詳解- ASP.NET 應用整合 SignalR 瀏覽器聊天室示例

在上一篇教程我們講解了SignalR 平臺配置要求,下面根據一步步詳細示例搭建一個 SignalR 的示例專案,以此瞭解 SignalR 到底是一個什麼樣的效果。 SignalR 示例所使用的軟體版本 Visual Studio 2013,當然更高的版本也是支援的。

動態生成頁面——ASP.NET中Literal使用

case colspan label 奇偶數 容器 業務邏輯 con stringbu font 在頁面中加入內容時,假設是靜態內容。無需使用容器,能夠直接將標記作為HTML直接加入到頁面中;可是,假設是動態內容,則必須借助容器將內容加入到頁面中。典型的容器

Asp.net web api中的坑-【api的返回值】

技術分享 要求 data 都是 blog pan odi handle 自己 void無返回值 IHttpActionResult HttpResponseMessage 自定義類型 我這裏並不想贅述這些返回類型, 可以參考博文http://blog.csdn.net/

asp.net -mvc框架復習1-ASP.NET網站開發概述

頁面設計 對象 ado 數據庫開發 sqlserve 網站 rip ado.net 面向對象 1.網站開發的基本步驟: 2.網站開發的需要的知識結構 (1)網站開發前臺頁面技術 頁面設計:HTML 、CSS+DIV 頁面特效:JavaScript、jQery (2)

asp.net -mvc框架復習5-ASP.NET MVC中的視圖簡單使用

font height logs 認識 知識 分類 ges mil c中 1.視圖分類 ASPX視圖(現在講解) Razor視圖(後面講解) ASPX 視圖: 2.@page指令 作用:頁面的聲明 要求:必須放在第一行,常用指令屬性如下: 3.服務器端內嵌

ASP.NET MVC關系

數據 調用 隱藏代碼 sql 實體 分析 model 返回 返回值 主項目引用 BLL Model BLL 業務邏輯層 引用DAL Model BLL是業務邏輯層,這裏面不寫sql語句,可以調用DAL層傳過來的值做判斷分析,並返回相應的值。最後在頁面的隱藏代碼中調用BLL的

HashMap底層實現原理/HashMap與HashTable區別/HashMap與HashSet區別

eem 實現原理 ger 銀行 索引 target 聲明 到你 們的 ①HashMap的工作原理 HashMap基於hashing原理,我們通過put()和get()方法儲存和獲取對象。當我們將鍵值對傳遞給put()方法時,它調用鍵對象的hashCode()方法來計算has

python+opencv實現動態物體追蹤

none apt iteration sim IT 技術 csdn while sso 原文鏈接:https://blog.csdn.net/cike14/article/details/50649811 import cv2 import numpy as np

ASP.NET—— ASP.NET基礎

msil 虛擬 語言 mvc .net 映射 pre 後置 文件 ASP.NET優勢(有了MVC後變成劣勢): 瀏覽器無關:生成的代碼遵循w3c 的XHTML標準,不同瀏覽器顯示的內容相同 易於調試:vs2010增加了JS調試功能 運行效率高:代碼先編譯成中間語音(MS

LayIM.AspNetCore Middleware 開發日記Asp.Net.Core.SignalR閃亮登場

you socket https image upm ogg 通訊 () aspnet 前言 ??前幾篇介紹了整個中間件的構成,路由,基本配置等等.基本上沒有涉及到通訊部分。不過已經實現了融雲的通訊功能,由於是第三方的就不在單獨去寫。正好.NET Core SignalR已