The PageMethods not invoking the code-behind method as expected

I've been attempting to call a simple code behind C# method using PageMethods (AJAX). I have set EnablePageMethods = true and made my code behind method as WebMethod public static. I even tried ScriptMethod with WebMethod but nothing seems to be working. I also attempted to modify the config file without any success.

 <script type="text/javascript">
    function ShowAvailability() {
        PageMethods.btnCheck_Click(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess)
    };
            function OnSuccess(response) {
                alert("On Success");
                var mesg = document.getElementById("mesg");
                switch (response) {
                    case "true":
                        mesg.style.color = "green";
                        mesg.innerHTML = "Available";
                        break;
                    case "false":
                        mesg.style.color = "red";
                        mesg.innerHTML = "Not Available";
                        break;
                    case "error":
                        mesg.style.color = "red";
                        mesg.innerHTML = "Error occured";
                        break;
                }
            }
            function OnChange(txt) {
                document.getElementById("mesg").innerHTML = "";
            }

            function test()
            {              
            }
</script>

<form id="form1" runat="server">
    <asp:ScriptManager ID="sm" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<div>
        UserName :
<asp:TextBox ID="txtUserName" runat="server"
    onkeyup="OnChange(this)"></asp:TextBox>
        <%--<asp:Button ID="btnCheck" runat="server" Text="Show Availability"  OnClientClick="btnCheck_Click(), return false;"></asp:Button>--%>
        <br />
        <button id="btncheck" onclick="ShowAvailability()">Show Availability</button>
        <span id="mesg"></span>

    </div>
</form>

Answer №1

When using OnClientClick, it is not possible to directly call a code behind method. Instead, it will call a script function named btnCheck_Click.

To implement this functionality: 

    <asp:Button ID="btnSearch" runat="server" ClientIDMode="Static" Text="Search" CssClass="button" OnClick="btnSearch_Click" />

In the code behind of the same page, include the following:

  protected void btnSearch_Click(object sender, EventArgs e)
    {
       //your code
    }

If you want to utilize ajax, declare the following on the client side:

To use ajax:


<asp:Button ID="btnSearch" runat="server" ClientIDMode="Static" Text="Search" CssClass="button" OnClientClick="btnSearch_Click()" />

Then, in the Script tag, call the ajax function:

function btnSearch_Click()
    { 
       jQuery.ajax({
                url: "Dashboard.aspx/getUserDetails", /* getUserDetails is a web method */
                type: "POST",
                data: jsondata,  /* jsondata= passed parameter in json format */
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) { },
                error: function () {
                    $('#Loadingimage').hide();
                    jAlert("Please try again later", 'Moderators');

                }
             });
    }

In Dashboard.aspx.cs, add the following code:

     [WebMethod]
    public static String getUserDetails(string strUserId)
    {
      return "";    /* for string only */
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic web designs can be achieved by utilizing a combination of technologies such as Ajax

Encountering issues while attempting to use Ajax and Fancybox.js photo viewer simultaneously. The website is initially set up as web 1.0 with standard navigation using hyperlinks. For html5 browsers, a JavaScript is utilized to create a web 2.0 experienc ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Open a customized form in jqGrid when the 'Edit' button is clicked, then refresh the row after editing

Whenever the user clicks on the 'Edit' button in a row of jqGrid, I want to open a customized form. This form should be triggered by the 'OnEdit' event and will display information about the selected row for editing. After making change ...

Efficiently packaging localized content into .NET satellite assemblies

We are in the process of transitioning a .NET Framework class library to .NET. One of the key functionalities of this library is parsing a .NET assembly, extracting any localizable resources, and creating satellite assemblies that contain localized version ...

Is ConcurrentQueue the right choice for optimizing performance in a HttpModule?

I'm currently in the midst of enhancing the speed of a HttpModule that processes images by implementing asynchronous programming techniques. Although there's a noticeable performance boost, I want to ensure that I am utilizing the available tool ...

Can PayPal sandbox accounts in Vue be used to process live transactions on a recently launched website?

I have completed the development of my app and now I am looking to host it online. Can I allow my clients to use sandbox accounts for real transactions? This is my first time creating an app with live online transactions using Paypal. Do I need to modify t ...

Can we specify ng-include, ng-init, and ng-controller within the controller definition?

<div class="row caption-view" ng-include="'app/views/inventory/grid-view/part.html'" module="subscriber" alias="il" ng-controller="GridController as il" ng-init="il.setGridParams(cse.gridParams.findCation); cse.find ...

The MasterPage event fails to trigger when attempting to fire the Required validation on the child page

In my ASP.net website, I have a Master page with a Button that navigates to the welcomePage. Below is the code behind for this functionality. protected void ImageButtonShortcut1_Click(object sender, ImageClickEventArgs e) { Response.Redirect("welcomePag ...

Ways to Update the Default Characters for Fallback

I'm looking to generate a plain ASCII text file from a string using File.WriteAllText with the Encoding.ASCII type: File.WriteAllText(_param.pathFileOut + "\\" + _param.batch_id + DateTime.Now.ToString("yyyyMMdd") + ".txt", _fileOut, Encodi ...

Struggling to get Deployd App to work, encountering issues with dpd.collection.first()

After successfully setting up the latest version of Deployd on my Windows 7 64 Bit system, I encountered an issue when trying to query a single object. For example, when using the code snippet below: var query ={"name":"Jack","empid":"10"}; dpd.employe ...

What is the best way to interact with WinForm components in a different class?

My form consists of a single button and two labels In addition to the form, I have created a separate class named myCounter I am looking for a way for the myCounter class to access the labels in the form using a method called changeColor.. How can I mak ...

Issue with Changing Active Class in Bootstrap Menu

I have been attempting various approaches to change the active class on a Bootstrap navbar (in Bootstrap 4), but I am facing difficulties. Each time I click on a new menu option, it momentarily changes to the active class before reverting back to 'hom ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...

When should we utilize the React.Children API in React applications?

Exploring the potential use cases of the React.Children API. The documentation is a bit confusing for me (Using React v.15.2.0). https://facebook.github.io/react/docs/top-level-api.html#react.children According to the documentation, this.props.children ...

What is the best way to extract the text from the first visible `<td></td>` table row using jQuery?

In this particular scenario, there is a table included: <table id="table"> <thead> <tr> <th>Name</th> <th>Course</th> </tr> </thead> <tbody> <tr style="display:none"> ...

Transforming JSON data into a Model-View-Controller

Although I have searched for answers to similar questions, the solutions I found do not seem to work in my case. I am attempting to pass JSON data to an MVC controller, but the controller is never being called. Any suggestions? Here is the Ajax call: fun ...

Retrieve various elements from an array in a JSON file using vb.NET and then connect them to a datatable

I'm in the process of developing a vb.net win form that utilizes a URL to fetch a json file which I need to insert into a datatable. I'm facing a challenge with organizing my public class hierarchy without ending up with too many lines of code. C ...

Utilized the select command to retrieve the selected value of a radiobutton within a gridview

In my current project using C# on ASP.NET, I have implemented radio buttons for selecting gender (MALE and FEMALE). I am able to save the values of these radio buttons to the database successfully. However, I am facing an issue with editing the gender info ...

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...