0

i have one function, which is named as callData() inside the c#. Now i want to call this function from JavaScript. I don't need any operations on JavaScript. Just i want to call that function. In this problem i don't need any other options.. Just i want to know how to call c# methods from JavaScript.

JavaScript

<script type="text/javascript">
function call()
    {
    //To call callData function

    }
</script>

Html code

 <html>
 <div>
 <asp:Button ID="hbtn" runat="server" OnClientClick="Javascript:call();"/>
 </div>
 </html>

C# code

public static void callData()
{
 //some operations
}
ragu
  • 165
  • 3
  • 6
  • 15
  • Show your work and tell us what have you tried so far.. Give people more informations.. – Soner Gönül Apr 02 '13 at 11:21
  • Dupicate: http://stackoverflow.com/questions/3994150/can-you-call-c-sharp-function-from-javascript many many question like this before! – Anh Tú Apr 02 '13 at 11:24
  • @AnhTú http://stackoverflow.com/questions/3994150/can-you-call-c-sharp-function-from-javascript this url just contains idea.. i need specific coding.. – ragu Apr 02 '13 at 11:37

2 Answers2

0

You can do this by making that C# function a web method with in a web service. Once you do that, you can make use of jQuery and call that function. To my knowledge you cannot just call a C# method within javascript.

Harish
  • 1,469
  • 16
  • 43
0

You will need to decorate your C# server-side method with the WebMethod attribute and make it static to expose it as a callable AJAX member:

[WebMethod]
public static void callData() {
  //some operations
}

Then use the ajax method, something like so, in your JavaScript method:

$.ajax({
  type: "POST",
  url: "path/to/page/callData",
  contentType: "application/json; charset=utf-8",
  data: {},
  dataType: "json",
  success: function (data) { },
  error: function (xhr, status, error) { }
});

Where successFn, and errorFn are functions to handle successful or failing outcomes respectively, such as.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129