Login Logout using jQuery Ajax in ASP.Net

Last Reply on Apr 28, 2017 04:51 AM By dharmendr

Posted on Apr 27, 2017 04:40 AM

Hi,

Can anyone suggest the code for login and logout using json and jquery in asp.net

Posted on Apr 28, 2017 04:51 AM Modified on one year ago

Hi JOYSON,

Refer the below sample. You can change the logic as per your requirement.

CS.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=btnLogin]").on("click", function () {
                var email = $("[id*=txtEmail]").val();
                var password = $("[id*=txtPassword]").val();
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/ValidateLogin",
                    data: '{email:"' + email + '",password:"' + password + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
            });
        });

        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            if (xml.find("Table").length > 0) {
                var firstName = xml.find("FirstName")[0].textContent;
                var lastName = xml.find("LastName")[0].textContent;
                window.location.href = "Logout.aspx?first=" + firstName + "&last=" + lastName;
            }
            else {
                alert('Email or password is not valid!');
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    User Email
                </td>
                <td>
                    <asp:TextBox ID="txtEmail" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    Password
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="btnLogin" Text="Login" runat="server" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

CS.aspx.cs

[System.Web.Services.WebMethod]
public static string ValidateLogin(string email, string password)
{
    string constr = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM [User] WHERE Email = @Email AND [Password] = @Password";
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query);
    cmd.Parameters.AddWithValue("@Email", email);
    cmd.Parameters.AddWithValue("@Password", password);
    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(constr))
    {
        using (System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (System.Data.DataSet ds = new System.Data.DataSet())
            {
                sda.Fill(ds);
                return ds.GetXml();
            }
        }
    }
}

Logout.aspx

<table>
    <tr>
        <td colspan="10">
            <asp:Label ID="lblName" runat="server" />
        </td>
        <td>
            <asp:HyperLink Text="logout" NavigateUrl="~/CS.aspx" runat="server" />
        </td>
    </tr>
</table>

Logout.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if ((Request.QueryString["first"] != null) || (Request.QueryString["last"] != null))
    {
        lblName.Text = "Welcome <b>" + Request.QueryString["first"] + " " + Request.QueryString["last"] + "<b/>";
    }
}

For VB.aspx change only the below line of javascript code.

url: "VB.aspx/ValidateLogin",

VB.aspx.vb

<System.Web.Services.WebMethod()> _
Public Shared Function ValidateLogin(email As String, password As String) As String
    Dim constr As String = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM [User] WHERE Email = @Email AND [Password] = @Password"
    Dim cmd As New System.Data.SqlClient.SqlCommand(query)
    cmd.Parameters.AddWithValue("@Email", email)
    cmd.Parameters.AddWithValue("@Password", password)
    Using con As New System.Data.SqlClient.SqlConnection(constr)
        Using sda As New System.Data.SqlClient.SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using ds As New System.Data.DataSet()
                sda.Fill(ds)
                Return ds.GetXml()
            End Using
        End Using
    End Using
End Function

Logout.aspx.vb

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If (Request.QueryString("first") IsNot Nothing) OrElse (Request.QueryString("last") IsNot Nothing) Then
        lblName.Text = "Welcome <b>" + Request.QueryString("first") + " " + Request.QueryString("last") + "<b/>"
    End If
End Sub

Screenshot