Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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     } 
like image 933
A. Sam John Christopher Avatar asked Apr 29 '11 06:04

A. Sam John Christopher


People also ask

Is it possible to call JavaScript function from Server Side?

You cannot just call JavaScript from server side.

Can we call JavaScript function from code behind C?

You cannot. Codebehind is running on the server while JavaScript is running on the client.

What is PageMethods in JavaScript?

PageMethods is a JavaScript class that is used to call code-behind functions via AJAX calls in the background. For example: You can use PageMethods to call a C# function on server-side. If PageMethods is not working in your application, there might be an implementation or post-back issue.


1 Answers

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> 
like image 170
Muhammad Akhtar Avatar answered Sep 29 '22 01:09

Muhammad Akhtar