Create Login Page using ASP.NET (Three Tier Architecture)


Step 1: Create SignIn.aspx page and write below code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SignIn.aspx.cs" Inherits="SignIn" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>:Login Panel:title>
head>
<body>
    <form id="frmLogin" runat="server">
    <div>
    <asp:Label ID="lblMsg" runat="server" Visible="false">asp:Label>
    div>
    <div style="width:50%; text-align:center">
    <table cellpadding="5" cellspacing="0" width="50%">
    <tr><td>User IDtd><td><asp:TextBox ID="txtUserId" runat="server">asp:TextBox>td>tr>
    <tr><td>Passwordtd><td><asp:TextBox ID="txtPass" TextMode="Password" runat="server">asp:TextBox>td>tr>
    <tr><td> td><td><asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />td>tr>
    table>
    div>
    form>
body>
html>

Step 2: Write below code in SignIn.aspx.cs page
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SignIn : System.Web.UI.Page
{
    blLogin objLogin = new blLogin();   //Login BL Object
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
          
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        CheckLogin();
    }

    protected void CheckLogin()
    {
        string strName;
        bool isVal = objLogin.ValidLogin(txtUserId.Text.Trim(), txtPass.Text.Trim(), out strName);
        if (isVal)
        {
            //store display name in session variable
            Session["Name"] = strName;
            lblMsg.Visible = true;
            lblMsg.Text = "Welcome" + strName; //or you can redirect to page
            //Response.Redirect("Home.aspx");
        }
        else
        {
            lblMsg.Visible = true;
            lblMsg.Text = "Sorry, Invalid User";
        }
    }
}

Step 3: Create class (Data Access Layer) with name of clsDAL.cs and write below code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;

///


/// Data Access Layer
///

///
    public class clsDAL
    {
        //connection string
        SqlConnection dbCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connString"].ToString());
        public clsDAL()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public void ExecuteNonQuery(string strQry)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strQry;
                cmd.Connection = dbCon;
                dbCon.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                dbCon.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //Execute Non Query by Param

        public void ExecuteNonQuery(string strQry, SqlParameter[] Parray)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddRange(Parray);
                cmd.CommandText = strQry;
                cmd.Connection = dbCon;
                dbCon.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                dbCon.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable getDataTable(string strQry)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                DataTable dt = new DataTable();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strQry;
                cmd.Connection = dbCon;
                dbCon.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                dt.Dispose();
                da.Dispose();
                cmd.Dispose();
                dbCon.Close();
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable getDataTable(string strQry, SqlParameter[] pArray)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                DataTable dt = new DataTable();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddRange(pArray);
                cmd.CommandText = strQry;
                cmd.Connection = dbCon;
                dbCon.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                dt.Dispose();
                da.Dispose();
                cmd.Dispose();
                dbCon.Close();
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
Step 4: Create class (Business Logic) with name of blLogin.cs and write below code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///


/// Summary description for blLogin
///

public class blLogin
{
    clsDAL objDAL = new clsDAL();   //Data Access Layer Object Initialization
      public blLogin()
      {
            //
            // TODO: Add constructor logic here
            //
      }

    public bool ValidLogin(string strUserName, string strPass, out string strName)
    {
        strName = "";
        DataTable dtLogin = objDAL.getDataTable("SELECT empName FROM EmployeeMaster WHERE UserId = '" + strUserName + "' AND Pass = '" + strPass + "'");
        if (dtLogin.Rows.Count > 0)
        {
            DataRow drLogin = dtLogin.Rows[0];
            strName = drLogin["empName"].ToString();
            return true;
        }
        else
        {
            return false;
        }
    }
}

Comments

anisha bathija said…
hey great article :)

but would you please elaborate on how I could make it better.
Suppose I have two roles - lets say a Admin and user.

how could I redirect the page to repective users .
whr shd i put a code to compare their roles from the db.
VedPathak said…
Hi Anisha,

Thanks a lot for your appreciation. Sorry for delayed. I am very much happy to hear you. Actually you can maintain the role via DB only making your roles table related to your login tables with Role ID which will redirect to specific page on logged in user via their Role(either Admin or User).
Or you can make one table with their log in Details and their Role as well and get the receptive role in bool value and Redirect to page.

I hope it will help you if not please let me know.
Thanks again.
Cheers,
ved pathak
Unknown said…
hiiii,Ved sir......):
I have three user Admin,Distributor and consumer..............
how could I redirect the page to repective users.
and your r giving one example 4 login
in this example which database table r u created.........plz maintaion
in comments
i understand this login example but which db table r u created i don't
understand..
plz...plz...plz..........):
VedPathak said…
Hi Rahul,

Sorry for delayed I will post you the proper Role Management system very soon.
Thanks
VarunK Palakkad said…
really helpful Article :)

Thank's
VARUN K
varunk1645@gmail.com
VedPathak said…
Hi Varun,
Thanks for your valuable time for feedback.I always open listen up all of you guys suggestions/feedback.
Thanks a ton!!
Cheers,
ved pathak
Unknown said…
how can we do it with execute scalar instead of datarow
Unknown said…
How can we do it login page using stored procedured in 3 tier in asp.net.
Unknown said…
How can we do it login page using stored procedured in 3 tier in asp.net.
Vikram said…
Thanks, if anyone want to check MVC version, you can check ASP.NET MVC login and Registration without EF

ASP.NET MVC login and registration
Thanks