1. 程式人生 > >Asp.net mvc+三層架構(註冊篇)

Asp.net mvc+三層架構(註冊篇)

                                               Asp.net mvc+三層架構(註冊篇)

先搞個簡單的SQL資料庫名為MVC, 新建表UserInfo

Id主鍵,int型,自增1;

UserName,char型;

PassWord,char型;

注意:表的名稱不要取user,因為與vs關鍵字有衝突,會報錯(尷尬地笑了一下)

 

專案結構:

 

1.新建一個名為MVCRegister的應用程式,並選擇mvc框架

 

2.分別建立DAL,BLL,Models類庫,再在DAL類庫下新建sql幫助類SqlHelper.cs

再在MVCRegister的目錄下的右鍵新增引用,在“程式集”勾選System.Cofiguration 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using
System.Threading.Tasks; 6 using System.Data.SqlClient; 7 using System.Configuration; 8 using System.Data; 9 using System.Collections; 10 11 namespace DAL 12 { 13 14 public class SqlHelper 15 { 16 17 public static string connString = ConfigurationManager.ConnectionStrings["
connString"].ToString(); 18 public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) 19 { 20 SqlCommand cmd = new SqlCommand(); 21 using (SqlConnection conn = new SqlConnection(connectionString)) 22 { 23 PrepareCommand(cmd, commandType, conn, commandText, commandParameters); 24 int val = cmd.ExecuteNonQuery(); 25 return val; 26 } 27 } 28 public static SqlDataReader GetReader(string sql) 29 { 30 SqlConnection conn = new SqlConnection(connString); 31 SqlCommand cmd = new SqlCommand(sql, conn); 32 try 33 { 34 conn.Open(); 35 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 36 37 } 38 catch (Exception ex) 39 { 40 throw ex; 41 } 42 } 43 44 45 public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues) 46 { 47 48 using (SqlConnection conn = new SqlConnection(connectionString)) 49 { 50 SqlCommand cmd = new SqlCommand(); 51 52 PrepareCommand(cmd, conn, spName, parameterValues); 53 int val = cmd.ExecuteNonQuery(); 54 55 return val; 56 } 57 } 58 59 public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) 60 { 61 62 SqlConnection conn = new SqlConnection(connectionString); 63 try 64 { 65 SqlCommand cmd = new SqlCommand(); 66 PrepareCommand(cmd, commandType, conn, commandText, commandParameters); 67 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 68 69 return rdr; 70 } 71 catch 72 { 73 conn.Close(); 74 throw; 75 } 76 } 77 78 public static SqlDataReader ExecuteReader(CommandType text, string connectionString, string spName, params object[] parameterValues) 79 { 80 SqlConnection conn = new SqlConnection(connectionString); 81 try 82 { 83 SqlCommand cmd = new SqlCommand(); 84 85 PrepareCommand(cmd, conn, spName, parameterValues); 86 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 87 88 return rdr; 89 } 90 catch 91 { 92 conn.Close(); 93 throw; 94 } 95 96 } 97 98 99 public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues) 100 { 101 using (SqlConnection conn = new SqlConnection(connectionString)) 102 { 103 SqlCommand cmd = new SqlCommand(); 104 105 PrepareCommand(cmd, conn, spName, parameterValues); 106 107 using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 108 { 109 DataSet ds = new DataSet(); 110 111 da.Fill(ds); 112 113 return ds; 114 } 115 } 116 } 117 118 119 public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) 120 { 121 using (SqlConnection conn = new SqlConnection(connectionString)) 122 { 123 124 SqlCommand cmd = new SqlCommand(); 125 126 PrepareCommand(cmd, commandType, conn, commandText, commandParameters); 127 using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 128 { 129 DataSet ds = new DataSet(); 130 131 da.Fill(ds); 132 133 return ds; 134 } 135 } 136 } 137 138 139 public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) 140 { 141 SqlCommand cmd = new SqlCommand(); 142 143 using (SqlConnection conn = new SqlConnection(connectionString)) 144 { 145 PrepareCommand(cmd, commandType, conn, commandText, commandParameters); 146 object val = cmd.ExecuteScalar(); 147 148 return val; 149 } 150 } 151 152 public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues) 153 { 154 SqlCommand cmd = new SqlCommand(); 155 156 using (SqlConnection conn = new SqlConnection(connectionString)) 157 { 158 PrepareCommand(cmd, conn, spName, parameterValues); 159 object val = cmd.ExecuteScalar(); 160 161 return val; 162 } 163 } 164 165 private static void PrepareCommand(SqlCommand cmd, CommandType commandType, SqlConnection conn, string commandText, SqlParameter[] cmdParms) 166 { 167 //開啟連線 168 if (conn.State != ConnectionState.Open) 169 conn.Open(); 170 171 //設定SqlCommand物件 172 cmd.Connection = conn; 173 cmd.CommandText = commandText; 174 cmd.CommandType = commandType; 175 176 if (cmdParms != null) 177 { 178 foreach (SqlParameter parm in cmdParms) 179 cmd.Parameters.Add(parm); 180 } 181 } 182 183 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, string spName, params object[] parameterValues) 184 { 185 //開啟連線 186 if (conn.State != ConnectionState.Open) 187 conn.Open(); 188 189 //設定SqlCommand物件 190 cmd.Connection = conn; 191 cmd.CommandText = spName; 192 cmd.CommandType = CommandType.StoredProcedure; 193 194 //獲取儲存過程的引數 195 SqlCommandBuilder.DeriveParameters(cmd); 196 197 //移除Return_Value 引數 198 cmd.Parameters.RemoveAt(0); 199 200 //設定引數值 201 if (parameterValues != null) 202 { 203 for (int i = 0; i < cmd.Parameters.Count; i++) 204 { 205 cmd.Parameters[i].Value = parameterValues[i]; 206 207 } 208 } 209 } 210 } 211 }
SqlHelper

 

3.在DAL中新建UserDAL.cs

 1 using Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Data.SqlClient;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace DAL
11 {
12    public  class UserDAL
13     {
14        
15         public int RegisterUserDAL(UserModels zhuce)
16         {
17             string sql1 = "insert into UserInfo (UserName,PassWord) values  ('{0}','{1}')";
18             sql1 = string.Format(sql1, zhuce.UserName, zhuce.PassWord);           
19             try
20             {
21                 SqlDataReader a = SqlHelper.GetReader(sql1);
22                 return 1;
23             }
24             catch
25             {
26                 return 0;
27             }
28         }
29 
30 
31     }
32 }
UserDAL.cs

 

在BLL中新建UserBLL

 1 using DAL;
 2 using Models;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace BLL
10 {
11     public class UserBLL
12     {
13         public int RegiterUserBLL(UserModels RegiterUser)//使用者註冊
14         {
15             int judge = new UserDAL().RegisterUserDAL(RegiterUser);
16             return judge;
17         }
18     }
19 }
UserBLL.cs

 

在Models中新建UserModels.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace Models
 9 {
10    public class UserModels
11     {
12         public int Id { get; set; }       
13         public string UserName { get; set; }
14         public string PassWord{ get; set; }
15 
16     }
17 }
UserModels.cs

 

4.新增Home控制器,Index是顯示註冊的介面,RegisterUser是實現註冊的方法

 1 using BLL;
 2 using DAL;
 3 using Models;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.Linq;
 7 using System.Web;
 8 using System.Web.Mvc;
 9 
10 namespace Pages.Controllers
11 {
12     public class HomeController : Controller
13     {
14         public ActionResult Index()
15         {
16             return View();
17         }
18         [HttpPost]
19         public ActionResult RegisterUser(UserModels Register)
20         {
21 
22              Register = new UserModels()
23             {
24                 UserName = Request.Params["UserName"],
25                 PassWord = Request.Params["PassWord"],             
26             };
27             UserBLL ret = new UserBLL();
28             if (ret.RegiterUserBLL(Register) == 1)//判斷是否插入成功
29             {
30                 return Content("<script>alert('註冊成功');window.location.href='../Home/Index';</script>");
31             }
32             else
33             {
34                 Response.Write("<script>alert('註冊失敗!')</script>");
35                 return View();
36             }
37             
38         }
39        
40 
41         }
42 }
Home

 

5.在Views資料夾下建Home資料夾,再建Index檢視

 1 @{
 2     Layout = null;
 3 }
 4 
 5 <!DOCTYPE html>
 6 
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11 
12 
13 </head>
14 
15 <body>
16     <div>
17         <%=Html.ValidationMessage("action") %>
18        <form method="post" action="/Home/RegisterUser">
19           
20                 <p>使用者名稱: <input name="UserName" type="text" /></p>
21                 <p>密&nbsp;碼: <input name="PassWord" type="text" /></p>
22                 <input type="submit" value="提交註冊" />
23             
24 
25         </form>
26         
27     </div>
28 
29 
30 </body>
31 </html>
Index

 

6.連線資料庫。開啟專案的Web.Config,在<configuration></configuration>標籤內,新增下面 語句 

<connectionStrings>
<add name="connString" connectionString="Data Source=.;Initial Catalog=Pages;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
</connectionStrings>

 

7.執行截圖

 

 

 

 

 

 

 




















</body></html>