GM-Xile GM-Xile
GM-Xile GM-Xile

Reputation: 321

Asp.net Checking Database before Form Action Executes

I am starting to learn Asp.net using C# Visual Studio. I am creating a simple Login Form and I have a little bit of a problem. I googled already yet I can't find the answer so I wanna try here maybe I can find one.

The problem is when I submit the form button, it should validate the inputs whether it is found in the database or not. If inputs are found, it should execute the form action, otherwise, do nothing.


LoginForm.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LoginForm.aspx.cs" Inherits="MajelFinals.LoginForm" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server" action="Success.aspx" lang="en" method="post" 
    name="frmLogin" submitdisabledcontrols="False">
    <div style="height: 252px">

        Login Form<br />
        <br />
        User ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
&nbsp;&nbsp;&nbsp;
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="txtUserID" ErrorMessage="* Required Input" 
            Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
        <br />
        <br />
        Password&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
&nbsp;&nbsp;&nbsp;
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="txtPassword" ErrorMessage="* Required Password" 
            Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
        <br />
        <br />
        <asp:Button ID="btnSignIn" runat="server" onclick="signIn_Click" 
            Text="Sign In" />

    </div>
    </form>
</body>
</html>

LoginForm.aspx.cs

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

namespace ProjectProject
{
    public partial class LoginForm : System.Web.UI.Page
    {
        private Login login;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void signIn_Click(object sender, EventArgs e)
        {
            UserLogin user = new UserLogin();
            user.userID = txtUserID.Text;
            user.userPass = txtPassword.Text;

            if (login.validateEntry(user)) //CHECKING IF FOUND IN THE DATABASE
            {
                   // CONTINUE
            }
            //STAY
        }
    }
}

Upvotes: 0

Views: 175

Answers (1)

Hossein
Hossein

Reputation: 25994

You usually have multiple choices when dealing with log-ins.
Usually when a log-in is tried, Upon a successful log-in , the user is redirected to another form. You can do either use (read more here):

 Response.Redirect("you page to process user actions, etc");

or yet better (Read more here),

 Server.Transfer("YourPage.aspx", true);  

And then do as you wish, usually in this step, you need to have a session prepared, so that in those pages you are redirecting, you can make a difference between a logged in user and some one who accidentally ( or intentionally ) tried to see the contents without logging in.
in this case when some one who failed stays at the log-in page as long as he enters a wrong log-in credential.

You may also use session and avoid redirecting, and by that session know when to do legitimate actions.
Meaning when a user enters a valid username or password, you create a session for it, and refresh the page, at page_load, you check to see if the session for the current user exists or not and the do what ever you need to do.
Session Example :

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.Session["ID"]!= null )
        {
            lblmsg.Text = "You are loged in";
        }
    }

    Dictionary<string, string> db = new Dictionary<string, string>(){
        {"Ali","XXX"},
        {"Alex","YYY"},
        {"Mina","zzz"},
        {"Admin","123"}
    };
    protected void Button1_Click(object sender, EventArgs e)
    {
       //simulating your database search
        if (db.Contains(new KeyValuePair<string,string>( txtBoxUser.Text,txtBoxPassword.Text)))
        {
            HttpContext.Current.Session["ID"] = txtBoxUser.Text;            
        }else
        {
            lblmsg.Text = "Not Logged in ";
        }
    }

You may also try to signal the same page, about a valid log-in, by sending some information to the same page using the post or get methods (post is more secure but i don't recommend it for this purpose at all).
When a user enters a valid username and password, you send his ID for example (Or some other cryptic info that only you know how to create and read, to avoid being simulated by other users) back to this page.
On page_load again you watch for this and if a valid value is found you know you have a successful log in, And then you can proceed to do what action you need to do.
For this to work , you also need to have a session or provide some mechanism which simulates one or each method or section of your page which needs an authentication , needs to use this method, which is cumbersome and not practical in my op pinion.

For POST method see this :
I would recommend using a session along with redirection to another page .

Upvotes: 1

Related Questions