Calling Server Side function from Client Side ScriptRecently I got requirement in my project that I have to check that ApplicationCode i.e Value entered by user is already available in database or not i.e unique value.
Output of the will look like as below if record exists its shows error "Record exists" otherwise it doesn't display any record.
Now in following post I am going to discuss about the what are the prerequisite need and why to use that.
Server Code
Below method get called from the client side script, as you can see there are some changes in the method attribute, declaration and definition which I am going to discuss
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
WebMethod Attribute
Attached WebMethod attribute with Public method indicates that the method exposed as part of the XML Web service. The attribute tells .NET that a particular public method is exposed as a web-callable method. To make use of this attribute you need to make use of System.Web.Services You can read about this attribute at : WebMethodAttribute Class
Static method
Static method is not associated with the instance of the class which get called by using only classname.methodname() i.e no need to create instance.
So that's why I marked method as static one. It cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls. Page methods are roughly equivalent to shorthand for standalone web services.
.CS file
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;//needed for the webmethod attribute
public
partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txtData.Attributes.Add("onblur", "focuslost()");
}
[WebMethod]
public static string IsExists(string value)
{
return "True";
}
}
in above code I have registered client event with onblur and attahced function focuslost.
Client Code on .ASPX page code
jQuery .ajax() call
To called method from the client side code I made use of the jQuery function called ajax to get more details about this function you can read about my blog post : Jquery Ajax Calling functions
function IsExists(pagePath, dataString, textboxid, errorlableid) {
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
In client script :
As I have to check code is exists or not I attached focusout() event with my textbox control, so when the focus get lost it make ajax call to the TextChanged event of code behind file.
url - Contains path of the page which is get called from the client side code i.e from aspx page.
data - Data sent to server from the client it basically json string.
contentType - Content type sent to server.
dataType - Expected data format from server
error - Called when call to server method fails
success - Called when call to server method is successes and return data from called method can be processed in this method
.Aspx page code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Async="true" Inherits="_Default" %>
<title></title>
<script src="JavaScript/jquery.js" type="text/javascript">
</script>
<script type="text/javascript">
function IsExists(pagePath, dataString, textboxid, errorlableid) {
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
</script>
<form id="form1" runat="server">
<asp:label id="lbl" runat="server" text="Enter unique value : "></asp:label>
<asp:textbox id="txtData" runat="server"></asp:textbox>
<div id="lblError" runat="server" style="display: none;">
Record exsits</div>
</form>
as in above code focuslost function get call IsExists function which in-turn call the serverside function and inform the entered value is unique or not.