此文是小白在学习张晨光老师的视频教学<
这一篇要练习的是,如下课程的代码:
新建项目:
因为这里小白用到的是mysql,所以引用:MySql.Data.dll大家可去官网自行搜索下载,index.aspx,login.aspx,login_new.aspx,ToolMysqlDate.cs是新添加的,后面会展开里面的代码.
bootstrap-5.1.3-dist文件夹里是Bootstrap5的前端组件库,从官网 getbootstrap.com 下载 Bootstrap 5.
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="MyMusci.login" %>
DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>title>
<link href="bootstrap-5.1.3-dist/css/bootstrap.css" rel="stylesheet" />
<script src="bootstrap-5.1.3-dist/js/bootstrap.bundle.js">script>
head>
<body>
<form id="form1" runat="server">
<%--这里引用Bootstrap5的模板 class="container mt-3"--%>
<div class="container mt-3">
<%--这里引用Bootstrap5的table的模板样式 class="table"--%>
<table class="table">
<tr>
<%--这里引用Bootstrap5的模板样式--%>
<td colspan="3" class="table-primary display-3 text-center text-primary">登录界面td>
tr>
<tr>
<td>账户td>
<td>
<asp:TextBox ID="userName" runat="server">asp:TextBox>
td>
<td>
<%--
**RequiredFieldValidator** 控件用于使输入控件成为一个必需(必填)的字段
ControlToValidate 要验证的控件的 id
Display 验证控件的显示行为 'Dynamic' 如果验证失败,控件显示错误消息.如果输入通过,页面上不预留显示消息的空间.
Text 当验证失败时显示的消息
ForeColor 控件的前景颜色
ErrorMessage 当验证失败时,在 ValidationSummary 控件中显示的文本(这里没有具体使用)
-%>
<asp:RequiredFieldValidator ID="rfv_useName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red">账户不可为空asp:RequiredFieldValidator>
<%--
**RegularExpressionValidator** 控件用于验证输入值是否匹配指定的模式
ControlToValidate 要验证的控件的 id
Text 当验证失败时显示的消息
ForeColor 控件的前景颜色
ErrorMessage 当验证失败时,在 ValidationSummary 控件中显示的文本(这里没有具体使用)
ValidationExpression 规定验证输入控件的正则表达式(此处\w{5,13}表示可以输入字符串,长度在5-13之间)
--%>
<asp:RegularExpressionValidator ID="rev_userName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{5,13}">您输入的账户异常(5-12位)asp:RegularExpressionValidator>
td>
tr>
<tr>
<td class="auto-style2">密码td>
<td class="auto-style2">
<asp:TextBox ID="userPwd" runat="server">asp:TextBox>
td>
<td class="auto-style2">
<asp:RequiredFieldValidator ID="rfv_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red">密码不可为空asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{8,13}">您输入的密码异常(8位)asp:RegularExpressionValidator>
td>
tr>
<tr>
<td>
<%--这里引用Bootstrap5的模板样式--%>
<asp:Button ID="btn_sub" runat="server" Text="登录" class="btn btn-primary" OnClick="btn_sub_Click" />
td>
<td>
<%--这里引用Bootstrap5的模板样式--%>
<asp:Button ID="btn_reset" runat="server" OnClick="btn_reset_Click" Text="重置" class="btn btn-secondary" />
td>
<td> td>
tr>
table>
div>
form>
body>
html>
后台代码:
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.Collections;
namespace MyMusci
{
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
///
/// 重置按钮点击事件
///
///
///
protected void btn_reset_Click(object sender, EventArgs e)
{
//将输入的值值空
userName.Text = "";
userPwd.Text = "";
}
///
/// 登录按钮点击事件
///
///
///
protected void btn_sub_Click(object sender, EventArgs e)
{
//先做测试,看看程序能不能跑起来
//if ("administrator".Equals(userName.Text) && "12345678".Equals(userPwd.Text)) {
// Response.Redirect("index.aspx");
//}
//从数据库中查寻用户名和密码
string sql = "SELECT COUNT(*) FROM user_all WHERE user_name=?name AND user_pwd=?pwd";
//之间的练习中一直用到,将前端文本框中的值填入Hashtable里(记得加引用哦)
Hashtable ht = new Hashtable();
ht.Add("name",userName.Text.ToString());
ht.Add("pwd", userPwd.Text.ToString());
//进行后台的聚合查询,返回查询到的值
int resilc=ToolMysqlDate.excutScal(sql,ht);
//如果数据库中有这个值
if (resilc > 0)
{
//将用户名绑定到Session
Session["userName"] = userName.Text.ToString();
//然后跳转至其他界面
Response.Redirect("index.aspx");
}
else {
//如果数据库查无此数据,就弹出提示框,告知用户
Response.Write("");
}
}
}
}
一.在Web.config中的configuration标签下添加如下代码:
<connectionStrings>
<add name="Conn_MyMusic" connectionString="Database='example';Data Source='127.0.0.1';User Id='root';Password='xxxxx';charset='utf8';pooling=true"/>
connectionStrings>
二.创建一个名为ToolMysqlDate.cs的类,并写入如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.Configuration;//所引用config,需要提前引用命名空间
using System.Collections;
using System.Data;
namespace MyMusci
{
public class ToolMysqlDate
{
//1.数据库的连接,创建等工作
public static string connstr = ConfigurationManager.ConnectionStrings["Conn_MyMusic"].ToString();
static MySqlConnection conn = new MySqlConnection(connstr);
//封装ExecuteScalar方法,返回值为int类型
public static int excutScal(String sql, Hashtable ht)
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);
//把ht传递过来之后,需要给参数赋值;
foreach (DictionaryEntry de in ht)
{
//第一个参数:key;第二个参数:value值
cmd.Parameters.AddWithValue(de.Key.ToString(), de.Value.ToString());
}
int result;
try
{
//运行并赋值
result = Convert.ToInt32(cmd.ExecuteScalar());
}
finally
{
conn.Close();
}
//返回
return result;
}
}
}
index.aspx里面并无填充其他内容,循序渐进吧,前端代码并未加任何控件,后台代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyMusci
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//如果能读取到Session对象,则显示相应的话
if (Session["userName"] != null)
{
Response.Write("欢迎:"+ Session["userName"].ToString()+"登录本页面");
}
//否则,提示错误,并返回至登录界面
else
{
Response.Write("");
Response.Redirect("login.aspx");
}
}
}
}
当输入不正确的用户名即密码:
当我们输入正确的用户及密码:
界面会自动跳转至登录界面
前端界面与login.aspx并无太大差别,只是将table嵌套入AJAX里,这样做的好处是节省时间,不耗费服务器资源:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login_new.aspx.cs" Inherits="MyMusci.login_new" %>
DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>title>
<link href="bootstrap-5.1.3-dist/css/bootstrap.css" rel="stylesheet" />
<script src="bootstrap-5.1.3-dist/js/bootstrap.bundle.js">script>
head>
<body>
<form id="form1" runat="server">
<div class="container mt-3">
<%--使用AJAX,先调用ScriptManager控件--%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<%--然后使用UpdatePanel控件,把登录界面的显示包裹进此控件中--%>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<%--因为不可之间进行包裹关系,所以先添加ContentTemplate,把代码放在ContentTemplate里--%>
<ContentTemplate>
<table class="table">
<tr>
<td class="table-primary display-3 text-center text-primary" colspan="3">登录界面td>
tr>
<tr>
<td>账户td>
<td>
<asp:TextBox ID="userName" runat="server">asp:TextBox>
td>
<td>
<asp:RequiredFieldValidator ID="rfv_useName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red">账户不可为空asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev_userName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{5,13}">您输入的账户异常(5-12位)asp:RegularExpressionValidator>
td>
tr>
<tr>
<td class="auto-style2">密码td>
<td class="auto-style2">
<asp:TextBox ID="userPwd" runat="server">asp:TextBox>
td>
<td class="auto-style2">
<asp:RequiredFieldValidator ID="rfv_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red">密码不可为空asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{8,13}">您输入的密码异常(8位)asp:RegularExpressionValidator>
td>
tr>
<tr>
<td>
<asp:Button ID="btn_sub" runat="server" class="btn btn-primary" OnClick="btn_sub_Click" Text="登录" />
td>
<td>
<asp:Button ID="btn_reset" runat="server" class="btn btn-secondary" OnClick="btn_reset_Click" Text="重置" />
td>
<td> td>
tr>
table>
ContentTemplate>
asp:UpdatePanel>
div>
form>
body>
html>
后台:
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.Collections;
namespace MyMusci
{
public partial class login_new : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
///
/// 重置按钮点击事件
///
///
///
protected void btn_reset_Click(object sender, EventArgs e)
{
userName.Text = "";
userPwd.Text = "";
}
///
/// 登录按钮点击事件
///
///
///
protected void btn_sub_Click(object sender, EventArgs e)
{
//测试
//if ("administrator".Equals(userName.Text) && "12345678".Equals(userPwd.Text)) {
// Response.Redirect("index.aspx");
//}
string sql = "SELECT COUNT(*) FROM user_all WHERE user_name=?name AND user_pwd=?pwd";
Hashtable ht = new Hashtable();
ht.Add("name", userName.Text.ToString());
ht.Add("pwd", userPwd.Text.ToString());
int resilc = ToolMysqlDate.excutScal(sql, ht);
if (resilc > 0)
{
//将用户名绑定到Session
Session["userName"] = userName.Text.ToString();
//Response是服务器发出的响应,耗费资源,服务器的内存和网络的带宽
//Response.Redirect("index.aspx");
//监听的控件id UpdatePanel1
//监听的控件类型 typeof(UpdatePanel)
//调用脚本的方法名 ok_login
//调用的脚本 alert('您已成功登录!');location.href='index.aspx'
//是否是javascript true
ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "ok_login", "alert('您已成功登录!');location.href='index.aspx'", true);
}
else
{
//Response.Write("");
ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "error_login", "alert('您输入的账户或密码有误,请核对后输入!!!')", true);
}
}
}
}