Search code examples
c#javascriptasp.netuser-controlswebmethod

Call Webmethod in Usercontrol.cs from Usercontrol.ascx javascript


I have a usercontrol and in that I have a javascript function which makes a call to webmethod.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="LeftMenu.ascx.cs"
Inherits="UserControls_LeftMenu" %>

<script type="text/javascript">

function GetRealTimeCount() {
    PageMethods.CountOfMenus('', '', GetCountOfMenus_Success, GetCountOfMenus_Fail);
}

My webmethod code is

[System.Web.Services.WebMethod]
public static string CountOfMenus(string StartDate, string EndDate)
{
    //Code here
}

But when I run the code, it gives me javascript error, CountOfMenus is undefined. I know the error is because it cant find the method in the current page but I want it to access method in the usercontrol.cs. I cant write the webmethod in every page as I have lots of pages where the usercontrol is used. Is there any way through which I can call the method of usercontrol.cs in javascript?


Solution

  • I solved this by below method

    Javascript :

    function GetRealTimeCount(StartDate, EndDate) {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var url = "Default.aspx?Method=CountOfMenus&SD=" + StartDate + "&ED=" + EndDate;
        xmlhttp.open("Get", url, false);
        xmlhttp.send(null);
        document.getElementById("Count").innerHTML = xmlhttp.responseText;
    }
    

    Code Behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Method"] == "CountOfMenus")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetCount(Request.QueryString["SD"], Request.QueryString["ED"]);
            }
        }
    
        private void GetCount(string StartDate, string EndDate)
        {
            Response.Clear();
    
            // Code to get count
    
            Response.Write(Count.ToString());
            Response.End();
        }
    

    The below link from where I got these solutions has many other options to call C# methods from javascript

    http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html