Search code examples
javascriptc#asp.netcode-behind

How to call a C# function from JavaScript?


I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!

JavaScript code:

if (Javascriptcondition > 0) {
   <%CsharpFunction();%>
}

C# code behind:

protected void CsharpFunction()
{
  // Notification.show();
}

How do I call a C# function from JavaScript?


Solution

  • You can use a Web Method and Ajax:

    <script type="text/javascript">             //Default.aspx
       function DeleteKartItems() {     
             $.ajax({
             type: "POST",
             url: 'Default.aspx/DeleteItem',
             data: "",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (msg) {
                 $("#divResult").html("success");
             },
             error: function (e) {
                 $("#divResult").html("Something Wrong.");
             }
         });
       }
    </script>
    
    [WebMethod]                                 //Default.aspx.cs
    public static void DeleteItem()
    {
        //Your Logic
    }