Sometimes we want to execute server side code from clientside using ajax then we can do this in two ways:-
- Using jQuery to directly call ASP.NET AJAX page methods.
- Using Script manager to access page methods.
- The Page Method should be static.
- Set the script manager enable PageMethods="true".
- Use java script PageMethods.<Method Name>(value, OnSucceeded, OnFailed).
- OnSucceeded - function to executed on success.
- OnFailed - function to executed on fail.
Default.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<html>
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function validatuser(soruce) {
var valueuseremail = soruce.value;
if (valueuseremail != "") {
PageMethods.ValidateUser(valueuseremail, OnSucceeded, OnFailed);
}
}
function OnSucceeded(result, usercontext, methodName) {
document.getElementById('<%= lblValidation.ClientID %>').innerHTML = result;
}
function OnFailed(error, userContext, methodName) {
alert("Error");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager
ID="ScriptManager"
runat="server"
EnablePageMethods="true" />
<asp:TextBox
ID="txtEmail"
runat="server"
onkeyup="validateuser(this);">
</asp:TextBox>
<asp:Label
ID="lblValidation"
runat="server">
</asp:Label>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ValidateUser(string struname)
{
string uerror = string.Empty;
try
{
bool userExists = false;
///
/// Check if user exists
///
if (struname.ToLower().Equals("bob"))
{ userExists = true; }
if (userExists)
{ uerror = "UserName already exists!"; }
else
{ uerror = "UserName available!"; }
}
catch
{
uerror = "Error";
}
return uerror;
}
}