The following is not properly work.
there were build errors.
Error 1 An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'.
Error 2 An object reference is required for the non-static field, method, or property '_Login.txtUsername'.
Error 3 An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Response.get'.
//Javascript Code
<script type="text/javascript">
$(function () {
$("[id*=btnlogin]").bind("click", function () {
var user = {};
user.Username = $("[id*=txtUsername]").val();
user.Password = $("[id*=txtPassword]").val();
$.ajax({
type: "GET",
url: "Login.aspx/ValidateUser",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
return false;
});
});
</script>
//HTML Code
<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" Text="" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnlogin" Text="Log In" runat="server" />
</td>
</tr>
</table>
</form>
//C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Services;
using System.Web.Script.Services;
public partial class _Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod]
public string ValidateUser(Users user)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_Admin"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password", user.Password);
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string IsValidate = string.Empty;
switch (userId)
{
case -1:
IsValidate = "Login Successfully..";
break;
case -2:
IsValidate = "Password is Incorrect..";
break;
case -3:
IsValidate = "Username and password is incorrect..";
break;
}
return IsValidate;
}
}
public class Users
{
public string Username { get; set; }
public string Password { get; set; }
}
//Stored Procedure
ALTER PROCEDURE dbo.Validate_Admin
(
@Username Varchar(40),
@Password Varchar(40)
)
As
if Exists
(
Select AdminId From Admin where Username = @Username And Password = @Password
)
SELECT -1 -- check for valid usrname and passwword
if Exists
(
Select AdminId From Admin where Username = @Username
)
SELECT -2 -- Username doesn't exist
SELECT -3 -- check for valid username