登录页面布局
<dl>
<dt>账号</dt>
<dd>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</dd>
<dt>密码</dt>
<dd>
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox>
</dd>
<dd></dd>
<dt>
<asp:Button ID="btnLogin" runat="server" Text="登录" OnClick="btnLogin_Click" />
</dt>
</dl>
效果图
当点击登录按钮时 -- 验证账号密码是否正确
一在Model中创建数据表
namespace Model
{
public class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Pwd { get; set; }
public int Role { get; set; }
}
}
二、在DAL中
1.DBhelper:
namespace DAL
{
public class SqlHelper
{
//连接字段
private static string strConn = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
//查询
public static DataTable Query(string sql)
{
SqlData adapter = new SqlData(sql, strConn);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
//非查询 using close
public static int NonQuery(string sql)
{
using (SqlConnection sqlConnection = new SqlConnection(strConn))
{
using (SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection))
{
sqlConnection.Open();
return sqlCommand.ExecuteNonQuery();
}
}
}
}
}
在UI层中的Web.config添加
<connectionStrings>
//db是名字,是要连接到DBhelper中的 catalog=数据库
<add name="db" connectionString="Data Source=.;Initial Catalog=DL;Integrated Security=True"/>
</connectionStrings>
例如:
2.在DAL中获取到账户密码
namespace DAL
{
public class UserInfoDAL
{
public static UserInfo Select(string name, string pwd)
{
//构建查询语句 = 不能使用like进行模糊查询
var sql = $"select * from UserInfo where name='{name}' and pwd='{pwd}'";
var table = SqlHelper.Query(sql);
//如果没有数据 null
if (table == null || table.Rows.Count < 1)
{
return null;
}
//如果有数据,取第一行,转换为对象
var row = table.Rows[0];
UserInfo user = new UserInfo()
{
Id = Convert.ToInt32(row["Id"]),
Name = Convert.ToString(row["Name"]),
Role = Convert.ToInt32(row["Role"])
};
return user;
}
//查询
//增删改
}
}
三、在BLL中调用DAL所写的方法
namespace BLL
{
public class UserInfoBLL
{
public static UserInfo Select(string name, string pwd)
{
return UserInfoDAL.Select(name, pwd);
}
}
}
四、当点击UI层中登录页面的登录按钮(用按钮的click事件),进行登录验证
protected void btnLogin_Click(object sender, EventArgs e)
{
//获取页面中的账号,密码
var user = UserInfoBLL.Select(txtName.Text, txtPwd.Text);
if (user == null)
{
Response.Write("<script>alert('账号或密码不正确')</script>");
}
else if (user.Role == 0)
{
//跳转到员工管理页面
Response.Redirect("yg.aspx");
}
else if (user.Role == 1)
{
//跳转到管理员管理页面
Response.Redirect("gl.aspx");
}
}