ASP.NET简单三层步骤
- 建立好相应的文件夹
文件夹 | 用处 |
---|---|
CURD.BLL | CURD的业务逻辑层 |
CURD.DAL | CURD的数据访问层 |
CURD.Model | CURD的传输层模型(本次将数据库模型与dto混为一谈) |
CURD.UI | CURD的网页端 |
CURD.UI
创建好模板Register.html1
2
3
4
5
6
7
8
9
10
11
12<form method="post" action="Register.ashx">
<label>loginid</label>
<input type="text" name="id">
<br>
<label>password</label>
<input type="password" name="password1">
<br>
<label>comfirm</label>
<input type="password" name="password2">
<br>
<input type="submit" value="注册"/>
</form>创建好Register的一般处理程序(请求页面)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string id = context.Request["id"];
string password1 = context.Request["password1"];
string password2 = context.Request["password2"];
//读取模板
string html = File.ReadAllText(context.Server.MapPath("Template/Register.html"));
if (id == null || password1 == null || password2 == null)
{
//第一次直接返回页面
context.Response.Write(html);
return;
}
if (password1 != password2)
{
//密码不正确返回,并替换告知
html = html.Replace("<input type=\"password\" name=\"password2\">",
"<input type=\"password\" name=\"password2\">两次密码不一致");
context.Response.Write(html);
}
else
{
//todo 插入注册信息,返回成功还是失败
}
}创建对应的Model
1
2
3
4
5
6
7
8
9namespace CURD.Model
{
public class User
{
public int AutoId { get; set; }
public string Id { get; set; }
public string Password { get; set; }
}
}只在dal层进行数据库操作
这里只添加一个方法,就是注册
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29public int Add(User user)
{
//可以设置成读取配置文件constr,返回成功1,失败-1
string constr = "data source=”LUOX78“的WIN;initial catalog=school;integrated security=true";
try
{
using (var con = new SqlConnection(constr))
{
string sql = "insert into Users(loginId,loginPwd) values(@id,@pwd)";
var pms = new SqlParameter[]
{
new SqlParameter("@id",user.Id),
new SqlParameter("@pwd",user.Password)
};
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddRange(pms);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
return -1;
}
return 1;
}bll调用dal并返回成功还是失败
1
2
3
4
5
6
7
8
9
10
11
12namespace CURD.BLL
{
public class UsersBll
{
private UsersDal db=new UsersDal();
public bool Add(User user)
{
return db.Add(user) == 1 ? true : false;
}
}
}UI层补全验证的步骤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15UsersBll userService = new UsersBll();
var res = userService.Add(new User()
{
Id = id,
Password = password1
});
if (res)
{
context.Response.Write("注册成功");
}
else
{
context.Response.Write("注册失败");
}