Call ASP.Net Page Method using jQuery AJAX Example

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {        
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
        
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <script src="Scripts/jquery-2.1.3.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function ShowCurrentTime() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetCurrentTime",
                    data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: OnSuccess,
                     failure: function (response) {
                         alert(response.d);
                     }
                 });
             }
             function OnSuccess(response) {
                 //alert(response.d);
                 $("#DivShowAfterClick").append("<p>" + response.d + "</p>");
                 $("#DivShowAfterClick").toggle();                
             }
        </script>

        <div>
            Your Name :
            <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
            <input id="btnGetTime" type="button" value="Show Current Time"
                onclick="ShowCurrentTime()" />
        </div>

        <div id="DivShowAfterClick" runat="server">This should be invisible until button clicked.</div>

    </form>
</body>
</html>

Source: http://aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

How To Get An Intelligible Error Message In a jQuery AJAX Call

Use xhr.responseText

Example:

function fcjDispose() {
            $.ajax({
                type: "POST",
                url: "PrintJHA.aspx/DisposeFCJ",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert("success");
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
            return false;
        };

Calling Web Service (asmx) From JavaScript Using PageMethods

TestService.ascx

namespace ScriptManagerService
{
    //The attribute which makes the web service callable from script.
    [System.Web.Script.Services.ScriptService]
    public class TestService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

The above web service code is pretty straight forward. We have a simple “HelloWorld” method which returns a string. What makes this web service special is the “[System.Web.Script.Services.ScriptService]” attribute added on top of the “TestService” web service class. The attribute makes the web service callable from JavaScript. Also when the proxy classes are generated the attribute generates JavaScript object corresponding to the web service class. Once the web service is created now we need to create our web page to invoke the web method. Create a new aspx page and add a “ScriptManager” control to it. Sample aspx page with the “ScriptManager” tag is added below.

<body>
<script language="javascript" type="text/javascript">
function invokeSimpleWebMethod()
{
    ScriptManagerService.TestService.HelloWorld(handleResult);    
} 
 
function handleResult(result)
{
    alert(result);
}

</script>

   <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="scrMgr" runat="server">
            <Services>
                <asp:ServiceReference Path="TestService.asmx" />                
            </Services>
        </asp:ScriptManager>
        <asp:Button ID="btnHW" runat="server" Text="Hello World" OnClientClick="invokeSimpleWebMethod();" />
    </div>
    </form> 
</body>

In the above code we can see that we have a “ScriptManager” server control added. And inside the “Services” tag we have added reference to our local web service using the “ServiceReference” tag. The path attribute of the “ServiceReference” tag has the url of the web service which needs to be invoked. You can add multiple web services by adding additional “ServiceReference” tags. What ASP.NET does here is that it generates JavaScript proxy classes for each of the web services mentioned in the “ServiceReference” tag. All the auto generated JavaScript proxy classes derive from “Sys.Net.WebServiceProxy”.

Also we have an ASP.NET Button server control which calls a “invokeSimpleWebMethod” javascript method on its “OnClientClick” event. In the “invokeSimpleWebMethod” javascript method we have made use of the namespace (in which the web service is defined) followed by the web service name and finally the method name which needs to be invoked. Behind the scene ASP.NET has done the extra work of registering the namespace and creating the proxy classes and also adding the methods defined inside the web service into a proxy JavaScript class. If you notice the “HelloWorld” method takes an argument. The argument is nothing but the name of the JavaScript function which needs to be invoked when the web service method has been successfully executed and results are returned to the browser. You can also pass the name of the function which needs to be invoked when the web service method invocation request fails. We will see the same shortly. The “handleResult” JavaScript method gets called when the asynchronous request is successfully returned. The method gracefully displays the result in an alert message box.

That’ about how to use the “ScriptManager” server control to invoke a web service methods i.e. namespace followed by class name followed by the method name. One thing to note is that “ScriptManager” control can only be used to call web services in the same domain.

More info from source and here.

Real World Example:

PollWSAsync.asmx

<%@ WebService Language="C#" Class="PollWSAsync" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// The following attribute allows the service to 
// be called from script using ASP.NET AJAX.
[System.Web.Script.Services.ScriptService]
public class PollWSAsync : System.Web.Services.WebService
{

    [WebMethod]
    public bool PollCastVote(int PollAnswerID)
    {

        bool returnValue = false;

        Guid userID = Guid.NewGuid();
        DateTime dateTimeStamp = DateTime.Now;

        // connection string
        string connectionString = ConfigurationManager.ConnectionStrings["PollConnectionString"].ConnectionString;

        // Sql connection object initialized with connection string used to connect
        using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
        {
            try
            {
                // open the Sql connection
                mySqlConnection.Open();

                // Sql Command object initialized with SQL INSERT
                SqlCommand mySqlCommand = new SqlCommand("INSERT INTO PollUserResponses (UserID, PollAnswerID, DateTimeStamp) VALUES (@UserID, @PollAnswerID, @DateTimeStamp)", mySqlConnection);
                mySqlCommand.Parameters.AddWithValue("@UserID", userID);
                mySqlCommand.Parameters.AddWithValue("@PollAnswerID", PollAnswerID);
                mySqlCommand.Parameters.AddWithValue("@DateTimeStamp", dateTimeStamp);

                // Execute
                mySqlCommand.ExecuteNonQuery();

                returnValue = true;

            }
            catch (Exception ex)
            {

            }
            finally
            {
                // close the Sql Connection
                mySqlConnection.Close();
            }

            return returnValue;

        }
    }
}

PollControlAsync.ascx

<script runat="server">
protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);      

    }
</script>
<script type="text/javascript">
    function CallService() {
        PollWSAsync.PollCastVote("1",
   Callback);
    }

    function Callback(result) {
        alert('CallBack Occured');
    }
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="PollWSAsync.asmx" />
    </Services>
</asp:ScriptManager>
<asp:Button ID="btnVote" runat="server" Text="Vote" OnClientClick="CallService();return false;" />

Calling Server Side Methods From Client Side Code Using PageMethods

<%@ Page Language="C#" %>

<script runat="server">
    
    [System.Web.Services.WebMethod]
    public static bool IsTicketAvailable(int NoOfTickets)
    {
        int AvailableTickets = 5;
        return (NoOfTickets > AvailableTickets);
    }


</script>

<html>
<head>
</head>
<body>
    <form id="form1" runat="server">
    <script language="javascript">
        function callserver() {
            var tic = $get("txtNoOfTic").value;
            PageMethods.IsTicketAvailable(tic, OnSuccess, OnFailure);
        }

        function OnSuccess(result) {
            if (result) {
                alert("Please enter less number of ticket!");
                $get("txtNoOfTic").select();
            }
        }

        function OnFailure(error) {
        }

</script>
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        No Of Tickets:
        <asp:TextBox ID="txtNoOfTic" onchange="callserver()" runat="server"></asp:TextBox>
    </div> 
    
    </form>
</body>
</html>

Source

Some notes about this implementation:

  1. Must be static methods and as such you can’t call a non-static method inside the static method
  2. [WebMethod] only works on pages (aspx), not controls (ascx)
  3. Works in both single file (inline) and codebehind ASPX implementations

How To Add A Scrollbar to an MS AJAX ToolKit AutoCompleteExtender

Create a DIV with it styled with an overflow-y:scroll to allow for vertical scrolling and set the height you want the dropdown to be. Within the AutoCompleteExtender define the CompletionListElementID equal to the ID of the DIV you just created.

<asp:TextBox runat="server" ID="txtBarcodeProduct" Width="400px"
CssClass="barcodeInput" TabIndex="5"></asp:TextBox>

<div id="listPlacement" style="height:100px; overflow-y:scroll;" ></div>

<cc1:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtBarcodeProduct"
ServicePath="~/webservices/AutoCompleteNew.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="12"
CompletionListElementID="listPlacement"
></cc1:AutoCompleteExtender>

How To AutoSave Using ASP.NET AJAX Controls

Using the Microsoft AJAX Toolkit. Add an UpdatePanel that contains a timer and an AlwaysVisibleControlExtender


    <asp:UpdatePanel ID="saveTimerUpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
    <Triggers>
    </Triggers>
    <ContentTemplate>
        <asp:Timer ID="saveTimer" runat="server"  Interval="3000" OnTick="saveTimer_Tick"></asp:Timer>
            <div id="savedDiv" runat="server" visible="false">
                <asp:Label ID="lblSaved" runat="server" Text="Auto-Save Successfull."></asp:Label>
            </div>
        <asp:AlwaysVisibleControlExtender ID="floatingSave" runat="server" 
        TargetControlID="savedDiv" ScrollEffectDuration=".1" HorizontalSide="Left" VerticalSide="Middle">
        </asp:AlwaysVisibleControlExtender>
    </ContentTemplate>
    </asp:UpdatePanel>

In the code behind:

  /// <summary>
        /// Handles the Tick event of the saveTimer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void saveTimer_Tick(object sender, EventArgs e)
        {
            if (this.savedDiv.Visible)
            {
                this.savedDiv.Visible = false;
                this.saveTimer.Interval = 300000;
            }
            else
            {              
                    if (SaveWhatEver())
                    {
                        this.savedDiv.Visible = true;
                        this.saveTimer.Interval = 4000;
                    }

                
            }
        }

How To Call Server Side Code From AJAX client-side

Markup:

In the AutoCompleteExtender OnClientItemSelected property add the JavaScript method to be called: OnClientItemSelected=”AutoCompletedClientItemSelected”

Within the AutoCompletedClientItemSelected JavaScript method issue a __doPostBack(“AutoCompleteExtender”, sender._element.value); which will induce the postback to the server.

<script language="javascript" type="text/javascript">
 // postBack handler for AJAX AutoComplete Extender - onClientItemSelected 
    function AutoCompletedClientItemSelected(sender, e) {        
        __doPostBack("AutoCompleteExtender", sender._element.value);
    }     
    
</script>

        <div id="find">
            <div id="findbox">
                <span class="label">JHA Name</span>
                <asp:TextBox ID="tbJHAName" CssClass="namebox" runat="server" AutoComplete="Off"
                    Width="550px" Style="margin-top: 0px"></asp:TextBox>
            </div>
            <asp:AutoCompleteExtender ID="tbJHAName_AutoCompleteExtender" runat="server" Enabled="true"
                ServicePath="" ServiceMethod="GetJHANames" TargetControlID="tbJHAName" MinimumPrefixLength="3"
                UseContextKey="True" OnClientItemSelected="AutoCompletedClientItemSelected">
            </asp:AutoCompleteExtender>
            <a id="linkAdvancedSearch" class="advancedlink" href="Javascript:void(0)" onclick="ShowAdvanced(this);">
                Advanced Search</a>
        </div>

Code Behind Page:

Filter the EventTarget message sent from the JavaScript method in the Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
             // postBack handler for AJAX AutoComplete Extender - JavaScript call: AutoCompletedClientItemSelected
                if (Request.Form["__EVENTTARGET"] != null &&               
                Request.Form["__EVENTTARGET"] == "AutoCompleteExtender" &&
                Request.Form["__EVENTARGUMENT"] != null)
                {
                    // Emulate button click search
                    btnSearch_Click(null, null);

                }
}

More details here