How to call a C# function from JavaScript?

IamNumber5 picture IamNumber5 · Aug 26, 2013 · Viewed 199.2k times · Source

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?

Answer

user3098137 picture user3098137 · Jun 20, 2014

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
}