ASP.Net登录框判断用户名和密码是否和数据库信息一致,一致则登录成功,不一致则登录失败
时间: 2024-01-14 16:04:51 浏览: 26
可以使用以下代码实现:
1. 在前端页面中,创建一个表单,包含用户名和密码的输入框,并设置提交按钮的事件。
```html
<form id="form1" runat="server">
<div>
<label for="txtUserName">用户名:</label>
<input type="text" name="txtUserName" id="txtUserName" />
</div>
<div>
<label for="txtPassword">密码:</label>
<input type="password" name="txtPassword" id="txtPassword" />
</div>
<div>
<input type="submit" name="btnSubmit" value="登录" onclick="return submitForm();" />
</div>
</form>
```
2. 在后端代码中,写一个验证用户名和密码的方法,连接数据库进行验证。
```csharp
protected bool ValidateUser(string userName, string password)
{
// 连接数据库,查询用户名和密码是否匹配
string connectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName=@UserName AND Password=@Password", connection);
command.Parameters.AddWithValue("@UserName", userName);
command.Parameters.AddWithValue("@Password", password);
connection.Open();
int count = (int)command.ExecuteScalar();
connection.Close();
// 返回验证结果
return count > 0;
}
```
3. 在前端页面的JavaScript中,编写submitForm函数,调用后端的验证方法,如果验证成功则跳转到主页面,否则提示用户登录失败。
```javascript
function submitForm() {
var userName = document.getElementById("txtUserName").value;
var password = document.getElementById("txtPassword").value;
// 调用后端的验证方法
if (PageMethods.ValidateUser(userName, password, onSuccess, onFail)) {
return true;
} else {
alert("用户名或密码错误!");
return false;
}
}
// 验证成功的回调函数,跳转到主页面
function onSuccess(result) {
if (result) {
window.location.href = "main.aspx";
}
}
// 验证失败的回调函数,提示用户登录失败
function onFail(error) {
alert("登录失败:" + error.get_message());
}
```
4. 在后端代码中,使用WebMethod标记验证方法,使其能够被前端页面的JavaScript调用。
```csharp
[System.Web.Services.WebMethod]
public static bool ValidateUser(string userName, string password)
{
// 验证用户名和密码是否匹配
// ...
// 返回验证结果
return true;
}
```