Ajax PageMethod
MS AJAX has gone one step further! We can now call methods in the codebehind of the current page from Javascript. Here's how:
Here i am tryin to Check whether the USERNAME Exists in my database.
----- Default.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
<asp:TextBox ID="TxtEventCode" runat="server" CssClass="StyleTextForm"
onblur="usernameChecker(this.value);"></asp:TextBox>
<span id ="spanAvailability"></span>
JavaScript part with the Script tag.
<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");
function usernameChecker(username) {
clearTimeout(usernameCheckerTimer);
if (username == "")
//if (username.length == 0)
spanAvailability.innerHTML = "Code cannot be Blank";
else {
spanAvailability.innerHTML = "checking...";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}
function checkUsernameUsage(username) {
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}
// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName) {
if (methodName == "IsUserAvailable") {
if (result == true)
//spanAvailability.innerHTML = "Available";
spanAvailability.innerHTML = "Already Exists";
else
spanAvailability.innerHTML = "Does Not Exist";
}
}
</script>
***** Do not forget to set the EnablePageMethods attribute to true. ******
------- Default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
namespace CheckUsernameWithAJAX
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
using System.Web.Services;
[WebMethod]
public static bool IsUserAvailable(string username)
{
SqlConnection cnn = new SqlConnection("data source=SYSTEMNAME; initial catalog=EVENTMGM; user ID=xxxx; Password=xxxx");
string Sqlstr;
//SqlCommand cmd = new SqlCommand();
//cmd.Connection= cnn;
//cmd.CommandType = CommandType.Text;
Sqlstr="SELECT USERNAME FROM USERLOG WHERE CODE = '" + username + "' ";
SqlDataAdapter da = new SqlDataAdapter(Sqlstr, cnn);
DataSet ds = new DataSet();
da.Fill(ds, "USERLOG");
//cmd.CommandText= Sqlstr;
//cnn.Open();
//int cnt = cmd.ExecuteNonQuery();
//cnn.Close();
if ( ds.Tables["HOTELMAS"].Rows.Count > 0)
return true;
else
return false;
//if (username.ToLower() == "travis")
// return false;
//else
// return true;
}
}
}
No comments:
Post a Comment