ASP.NET简单的系统登录

来源:互联网 发布:淘宝店铺业绩查询 编辑:程序博客网 时间:2024/05/31 19:33

用ASP.NET编写的系统登录和之前的C/S差别还是挺大的,看完视频,自己也敲了一个系统登录的例子,介绍一下例子中涉及到的知识点:

一、Page_Load事件以及IsPostBack属性

Page_Load事件是窗体的加载事件,IsPostBack属性判断窗体是不是第一次加载,窗体加载的时候通过IsPostBack属性可以检查.aspx页是否为传递回服务器的页面。

判断窗体是不是第一次加载的代码:

if (!Page.IsPostBack){   this.txtUserName.Text = "";   this.txtUserPwd.Text = "";}

一、ASP.NET中的对象:

Request:发送从浏览器向服务器的请求信息,用户在提交表单时,包含在输入控件上的数据一起被发送。

Request对象中常用的两个属性集:Form和QueryString

Request中表单的两种提交方式:post和get

提交到服务器的方式不同,代码编写中有一定的差异:

默认采用post方式:

string userName = Request["txtUserName"].ToString();string userPwd = Request["txtUserPwd"].ToString();string userName = Request.Form.Get("txtUserName").ToString();string userPwd = Request.Form.Get("txtUserPwd").ToString();

 采用get方式:

string username=Request.QueryString["txtUserName"].ToString();string userPwd=Request.QueryString["txtUserPwd"].ToString();

系统登录实例:

首先编写一个HTML页面作为登录界面,使用Dreamweaver设计的界面如下:

在项目中直接引用刚刚创建的.html文件,在文件表单中指定action


然后创建数据库


添加一个Web窗体:login.aspx,后台代码编写:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.SqlClient;namespace Test2_1{    public partial class login : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {//通过Request获得传入到服务器端的属性            string userName = Request.Form["userName"].ToString();            string userPwd = Request.Form.Get("userPwd").ToString();            //连接数据库            SqlConnection con = new SqlConnection("server=.;database=ASP.NET;uid=sa;pwd=123456;");            con.Open();            SqlCommand cmd = new SqlCommand("select count(*) from LoginInfo where userName='"+userName+"'and userPwd='"+userPwd+"'",con);            int count =Convert.ToInt32(cmd.ExecuteScalar());            if (count>0)            {                //加上问号,就变成了get提交                Response.Redirect("main.aspx?userName="+userName);            }            else            {                Response.Redirect("loginFail.html");            }        }    }}

然后依次添加main.aspx窗体和loginFail.html:


在main.aspx中编写代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Test2_1{    public partial class main : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //采用get提交方式可以直接调用传入的userName            string userName=Request.QueryString["userName"].ToString();            Response.Write("<font size=20 color=red>欢迎" + userName + "进入本网站</font>");        }    }}

在loginFail.html中添加一个超链接:


运行程序:

输入错误的用户名和密码:


运行结果:


点击返回转到登录界面:

输入正确的用户名和密码:


运行结果:


系统登录成功了!

总结这个例子,主要讲了Page_Load事件和IsPostBack属性,Request和Response对象的使用,使用Dreamweaver制作网页以及数据库的连接。

学习之路,任重道远!


0 0
原创粉丝点击