locked
Calling c# method using JavaScript in ascx page RRS feed

  • Question

  • User-817945037 posted
    Hi,

    I am using SharePoint Visual webpart where in I have to use JavaScript or JQuery to call c# method on drop down selected index change to avoid postback.

    I have used following code

    <asp:DropDownList ID="drpClient" runat="server" DataTextField="ClientName" DataValueField="ClientID" onchange="GetCountryDetails()"></asp:DropDownList>

    Below is the JavaScript function.

     <script type="text/javascript">

     function GetCountryDetails() {             debugger;                       var parm = document.getElementById('<%= drpClient.ClientID %>');             var strCountry = parm.options[parm.selectedIndex].text;             var SelectedText = strCountry;             var SelectedVal = parm.options[parm.selectedIndex].value;

                alert(SelectedVal);

                                 $.ajax({                     type: "POST",                     url: 'Client.aspx/GetPreviousMonthServiceData1',                     data: "",                     contentType: "application/json; charset=utf-8",                     dataType: "json",                     success: function (result) {                         if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {                             CallBackFunction(result);                         }

                        },                     error: function (result) {                         alert('error occured');                         alert(result.responseText);                         //window.location.href = "FrmError.aspx?Exception=" + result.responseText;                     },                     async: true                 });                      }

        </script>

    C# code in ascx.cs  is:

    publicstaticvoidGetPreviousMonthServiceData1()

            {

            }

    It is not working... It always throws exception saying - Unknown Web method...

    Tuesday, October 13, 2015 9:42 AM

Answers

  • User753101303 posted

    Do you have a [WebMethod] attribute on your C# method to make it explicitely available through http?

    Also in the toolbar for yourpost, you have an "insert code" button before the "help" (last) buttton. Your code will be formated such as :

    [System.Web.WebServices.WebMethod]
    public static void GetPreviousMonthServiceData1()
    {
       // some code here
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 13, 2015 10:08 AM
  • User61956409 posted

    Hi shreyasrs,

      $.ajax({                     type: "POST",                     url: 'Client.aspx/GetPreviousMonthServiceData1',                     data: "",                     contentType: "application/json; charset=utf-8",                     dataType: "json",                     success: function (result) {                         if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {                             CallBackFunction(result);                         }

                        },                     error: function (result) {                         alert('error occured');                         alert(result.responseText);                         //window.location.href = "FrmError.aspx?Exception=" + result.responseText;                     },                     async: true                 });

    According to your code, it seems that you’d like to call webmethod using jQuery AJAX. Please make sure you assign a correct value to “url” option. Besides, the following articles explained how to make a call to ASP.Net WebMethod using jQuery AJAX, hoping they will be helpful.

    http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

    http://www.c-sharpcorner.com/Blogs/46672/calling-a-webmethod-using-jquery-ajax.aspx

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2015 4:05 AM
  • User-1667135504 posted

    Instead of ASCX use ASMX [WebService]. Below code will help you in making a jquery ajax call.

    jQuery code: On dropdownlist change event call a jQuery Ajax Method [WebMethod]

    $("#drpClient").on('change',function(){
    	
        var self=$(this);
        var get_text=self.val();
        var get_id=self.find('option:selected').text();
     
        var aData= [];
        aData[0] =get_id; 
       
        var jsonData = JSON.stringify({ aData:aData});
        $.ajax({
            type: "POST",
            url: "WebService.asmx/TestMethod", 
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json", // dataType is json format
            success: OnSuccess,
            error: OnErrorCall
        });
       
        function OnSuccess(response) {
    		 var result=response.d;
    		 alert(result);
    
        }
        function OnErrorCall(response) { console.log(error); }
    
    });

    Server side: Create a webmethod

    [WebMethod]
    public string  TestMethod(List<string> aData)
    {
    	// code logic here
    	return "result";
    }


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2015 5:38 AM

All replies

  • User753101303 posted

    Do you have a [WebMethod] attribute on your C# method to make it explicitely available through http?

    Also in the toolbar for yourpost, you have an "insert code" button before the "help" (last) buttton. Your code will be formated such as :

    [System.Web.WebServices.WebMethod]
    public static void GetPreviousMonthServiceData1()
    {
       // some code here
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 13, 2015 10:08 AM
  • User-817945037 posted

    Hi PatriceSc,

    Thanks for the suggestion... will format the code next time...

    Regarding the solution, I tried by putting [WebMethod] attribute on your C# method but still same error!!

    Tuesday, October 13, 2015 1:02 PM
  • User61956409 posted

    Hi shreyasrs,

      $.ajax({                     type: "POST",                     url: 'Client.aspx/GetPreviousMonthServiceData1',                     data: "",                     contentType: "application/json; charset=utf-8",                     dataType: "json",                     success: function (result) {                         if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {                             CallBackFunction(result);                         }

                        },                     error: function (result) {                         alert('error occured');                         alert(result.responseText);                         //window.location.href = "FrmError.aspx?Exception=" + result.responseText;                     },                     async: true                 });

    According to your code, it seems that you’d like to call webmethod using jQuery AJAX. Please make sure you assign a correct value to “url” option. Besides, the following articles explained how to make a call to ASP.Net WebMethod using jQuery AJAX, hoping they will be helpful.

    http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

    http://www.c-sharpcorner.com/Blogs/46672/calling-a-webmethod-using-jquery-ajax.aspx

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2015 4:05 AM
  • User-1667135504 posted

    Instead of ASCX use ASMX [WebService]. Below code will help you in making a jquery ajax call.

    jQuery code: On dropdownlist change event call a jQuery Ajax Method [WebMethod]

    $("#drpClient").on('change',function(){
    	
        var self=$(this);
        var get_text=self.val();
        var get_id=self.find('option:selected').text();
     
        var aData= [];
        aData[0] =get_id; 
       
        var jsonData = JSON.stringify({ aData:aData});
        $.ajax({
            type: "POST",
            url: "WebService.asmx/TestMethod", 
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json", // dataType is json format
            success: OnSuccess,
            error: OnErrorCall
        });
       
        function OnSuccess(response) {
    		 var result=response.d;
    		 alert(result);
    
        }
        function OnErrorCall(response) { console.log(error); }
    
    });

    Server side: Create a webmethod

    [WebMethod]
    public string  TestMethod(List<string> aData)
    {
    	// code logic here
    	return "result";
    }


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2015 5:38 AM