Create a login module using Entity Framework

If you are new to Entity Framework then read my earlier blog on this.
In this blog I will explain about how to create a login module using entity framework.

Create a login module using Entity Framework

Create Table Script:

/****** Object:  Table [dbo].[Admin]    Script Date: 16/08/2016 10:45:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Admin](
       [id] [int] IDENTITY(1,1) NOT NULL,
       [userid] [varchar](255) NULL,
       [password] [varchar](255) NULL,
       [role] [int] NULL,
       [active] [bit] NULL,
 CONSTRAINT [PK_backend] PRIMARY KEY CLUSTERED
(
       [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Once table created insert a record to test.

Now add ADO.Net Entity Data Model and write below code for login module.

ASPX Content:

    <asp:PlaceHolder runat=”server” ID=”ErrorMessage” Visible=”false”>
                       
      <asp:Literal runat=”server” ID=”FailureText” />
                         
    </asp:PlaceHolder>
<asp:TextBox runat=”server” ID=”TxtUserName” />
<asp:TextBox runat=”server” ID=”TxtPassword” TextMode=”Password”/>
<asp:Button runat=”server” OnClick=”LogIn” Text=”Log in” />

.Cs Code:


protected void LogIn(object sender, EventArgs e)
    {
        string userid = TxtUserName.Text.Trim();
        string password = TxtPassword.Text.Trim();
        if (IsValid)
        {
            try
            {
                using (var ctx = new TestEntities())
                {
                    var data = ctx.backends
       .Where(b => b.userid == userid && b.password == password)
       .FirstOrDefault();
                    if(data!=null)
                    {
                        int? role = data.role;
                        Session[“role”] = role.ToString();
                        Session[“admin”] = data.userid.ToString();
                        Response.Redirect(“default.aspx”,true);
                    }
                    else
                    {
                        FailureText.Text = “Invalid User ID/Password”;
                        ErrorMessage.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

Leave a Comment

RSS
YouTube
YouTube
Instagram