ASP.NET学习笔记--自己写的Login.aspx
以前有大学有学过,但是没学好,现在准备完全自己动手做一个网站,学习一下ASP.NET
做一个登录页面,首先要有创建一个新的网站,添加Login.aspx,然后做出自己想要的DIV和CSS布局,
之后创建自己的数据库,代码如下:
USE [master] GO IF EXISTS(SELECT * FROM dbo.sysdatabases where dbid=DB_ID('MyStore')) DROP DATABASE MyStore GO CREATE DATABASE [MyStore] GO USE [MyStore] GO CREATE TABLE [VIP_USER] ([User_Id] INT PRIMARY KEY IDENTITY, [User_Name] CHAR(50) NOT NULL, [User_Password] CHAR(50) NOT NULL ) GO INSERT INTO [VIP_USER] VALUES('tangxuelong','Password@1')
下一步就要准备链接数据库了,首先在webconfig的connectString中写入自己的链接字符串,
然后项目添加一个类库,DAL,DAL中添加DBhelper类,这时候给DBhelper添加System。configuration的引用
之后是代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace DAL { public class DBhelper { public SqlConnection Getcoon(){ string Sql = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //获取链接字符串 SqlConnection conn = new SqlConnection(Sql); return conn; } } }
给项目添加对DAL类库的引用之后
下一步双击Login.aspx中的登录按钮,给它添加click时间代码,
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DAL; //添加对DAL命名空间的引用 using System.Data; using System.Data.SqlClient; namespace MyStore { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string userName = "innite"; //初始化 string password = "innite"; DBhelper db = new DBhelper(); //对象实例化才能调用类中的public方法 SqlConnection conn = db.Getcoon(); if (conn.State.Equals(ConnectionState.Open))//判断数据库是否已被打开 { conn.Close(); } conn.Open();//打开数据库连接 string sql = "select User_Name,User_Password from VIP_USER"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandType = CommandType.Text; try { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { userName = reader[0].ToString(); password = reader[1].ToString(); } } catch (Exception msg) { Response.Write("<script>alert(" + msg + ");</script>"); } finally { conn.Close(); cmd.Dispose(); } if (ValidateUser(userName, password)) { Response.Redirect("~/Main.aspx"); } else { Response.Write("<script>alert('用户名或密码无效!请重新输入!');</script>"); } } public Boolean ValidateUser(string UserName, string Password) //验证用户名和密码 { if (UserName.Trim()!= TextBoxusername.Text.Trim()||Password.Trim()!=Textpassword.Text.Trim()) { return false; } else { return true; } } } }
F5运行,完成登录后跳转到Main.aspx中。
完全菜鸟,不足之处很多,大神若有指教,感激不尽。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步