[c#] How to call code behind server method from a client side JavaScript function?

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    
}

This question is related to c# javascript .net asp.net

The answer is


Try creating a new service and calling it. The processing can be done there, and returned back.

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

aspx code:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}

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

RegisterPostbackTrigger(idOfButton)

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)
{

}

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


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();
}

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        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
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

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>

Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()

You'll end up writing something like this:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    // do something when done
  }
});

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery