Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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
}
share|improve this question
 
Show your work and tell us what have you tried so far.. Give people more informations.. –  Soner Gönül Apr 2 at 11:21
 
Dupicate: stackoverflow.com/questions/3994150/… many many question like this before! –  Anh Tú Apr 2 at 11:24
 
@AnhTú stackoverflow.com/questions/3994150/… this url just contains idea.. i need specific coding.. –  ragu Apr 2 at 11:37
 
thanks @PatrickMcDonald –  ragu Apr 2 at 11:39
add comment

marked as duplicate by Patrick McDonald, dreamlax, Tomas Lycken, Bergi, AppDeveloper Apr 2 at 13:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

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.

share|improve this answer
add comment

This question has already been answered by many people.Even it,I would suggest you the best answer for this over here.Please click here

share|improve this answer
add comment

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.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.