用linq实现登陆功能

BLL层的逻辑代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class Class1
    {
        public bool IsLogin(string name, string pwd,out string msg)
        {
	    //创建linq对象
            DataClasses1DataContext context = new DataClasses1DataContext();
	    //得到linq中数据库的表
            var stu = context.student;
            //根据账号得到一个用户名  判断用户是否存在  如果存在则判断密码是否正缺
            //如果不存在则提示用户不存在
            var student = context.student.Where(p => p.username == name).FirstOrDefault();
            if (student == null)
            {
                msg = "用户不存在";
                return false;
            }
            else if (student.password != pwd)
            {
                msg = "密码错误";
                return false;
            }
            else
            {
                msg = "登录成功";
                return true;
            }
        }
    }
}

 页面中的代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            账号:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
            密码:<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox><br />
            <asp:Label ID="lbShow" runat="server" Text=""></asp:Label>
            <asp:LinkButton ID="lbLogin" runat="server" OnClick="lbLogin_Click">登录</asp:LinkButton>
        </div>
    </form>
</body>
</html>

 页面的后置代码

using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void lbLogin_Click(object sender, EventArgs e)
    {
	//得到再文本中输入的内容
        string name = this.txtUserName.Text.ToString();
        string pwd = this.txtPwd.Text.ToString();
	//创建业务逻辑层中类的对象
        Class1 cl = new Class1();
        string msg = "";
	//判断是否登录成功
        if (cl.IsLogin(name, pwd, out msg))
        {
            this.lbShow.Text = msg;
        }
        else
        {
            Response.Redirect("index.aspx");
        }
    }
}

 

posted @ 2013-09-18 09:44  流浪的狸猫  阅读(780)  评论(0编辑  收藏  举报