How to call code behind server method from a client side JavaScript function?

271,492

Solution 1

Yes, you can make a web method like..

[WebMethod]
public static String SetName(string name)
{
    return "Your String"
}

And then call it in JavaScript like,

PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);

This is also required :

<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>

Solution 2

In my projects, we usually call server side method like this:

in JavaScript:

document.getElementById("UploadButton").click();

Server side control:

<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />

C#:

protected void Upload_Click(object sender, EventArgs e)
{

}

Solution 3

If you dont want to use ajax than

Code behind 

void myBtn_Click(Object sender,EventArgs e)
{
   //SetName(name); your code
}


.aspx file

<script language="javascript" type="text/javascript">
    function btnAccept_onclick() {        
        var name;            
        name = document.getElementById('txtName').value;
        document.getElementById('callserver').click();
        // Call Server side method SetName() by passing this parameter 'name'
</script>


<div style="dispaly:none;">
  <input type="button" id="callserver" value="Accept" click="myBtn_Click" runat="server" />
</div>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />

or use page method

.cs file
[ScriptMethod, WebMethod]

   public static string docall()
   {
      return "Hello";
   }

.aspx file

<script type="text/javascript">
      function btnAccept_onclic() {
          PageMethods.docall(onSuccess, onFailure);
      }

  function onSuccess(result) {
          alert(result);
      }


      function onFailure(error) {
          alert(error);
      } 

</script>

check this : http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

Solution 4

JS Code:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

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

Solution 5

I had to register my buttonid as a postbacktrigger...

RegisterPostbackTrigger(idOfButton)
Share:
271,492
A. Sam John Christopher
Author by

A. Sam John Christopher

Updated on July 24, 2020

Comments

  • A. Sam John Christopher
    A. Sam John Christopher almost 4 years

    I am having an JavaScript function for a HTML button click event in ASPX page. And a server Method in its code behind page. Now i want to call the server method from the JavaScript function with some parameters only when the HTML button is clicked by the user.

    Please don't change this scenario and also don't use any asp.net contols in the aspx page while replying. Because only HTML controls are allowed. Can anyone help me on this ?. Thanks in advance. Eagerly waiting for answers.

    Here is the code,

    Code in markup:

    <script language="javascript" type="text/javascript">
        function btnAccept_onclick() {        
            var name;            
            name = document.getElementById('txtName').value;
    
            // Call Server side method SetName() by passing this parameter 'name'
    </script>
    
    <input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />
    

    Code-behind:

    public void SetName(string name)
    {
        // Code for some functionality    
    }
    
  • A. Sam John Christopher
    A. Sam John Christopher about 13 years
    Thank you for your quick response but don't use any controls (asp.net or HTML) having runat="server" tag in the aspx page. And also avoid ajax as possible.
  • Pranay Rana
    Pranay Rana about 13 years
    well second method without any server tags but you need to user pagemethod which use ajax
  • 1teamsah
    1teamsah over 9 years
    Hi. This is working fine if there is a click method for my project. I've 2 js function and 2 different onclick method in 2 different asp buttons. One method be called, but the other one uncalled. How is it possible?
  • sab669
    sab669 almost 9 years
    While debugging, I get this error: JavaScript runtime error: Unable to get property 'click' of undefined or null reference. The button is there on my aspx file and in the code behind it is defined with the event handler attached. Any idea?
  • Phiter
    Phiter over 7 years
    @sab669, by using his method you'll face a small problem where the ClientID is not the same as the server ID. Add the extra attribute ClientIDMode = "Static" so the Client ID and Server ID will be the same.
  • fix
    fix over 7 years
    Are there any security concerns when enabling PageMethods? I'm wondering why it's disabled by default.