How to call code behind method from a javascript function?
Solution 1
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
Solution 2
The WebMethods that are defined must be "static".
The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!
$.ajax({
type: "POST",
url: 'GenerateEAInHtml.aspx/GetAllRegions',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
The WebMethod is defined this way:
[WebMethod]
public static List<Region> GetAllRegions()
{
/* Your Code goes here */
return regions;
}
You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.
Solution 3
Assumption that your page name is abc.aspx and xyz is the function name that you have to call. javascript :
function sendData(offset) { $.ajax({ type: "POST", url: "abc.aspx/xyz", contentType: "application/json; charset=utf-8", dataType: "json" }); }
Server Side : add Imports System.Web.Script.Serialization
WebMethod(enableSession:=True) _ Public Shared Function xyz() As String your code here End Function
Add module in web.config -> system.webServer
->system.webServer> ->modules> ->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> ->/modules> ->/system.webServer>
Solution 4
Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.
user2729114
Updated on July 09, 2022Comments
-
user2729114 almost 2 years
I am having an javascript function for a HTML img 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 without any parameter only when the HTML img is clicked by the user.
C# Code Behind Method:
[WebMethod] public void PopUpClick(object sender, EventArgs e) { //Something; }
JavaScriptMethod:
$(document).ready(function () { $('.clickme').click(function () { PageMethods.PopUpClick(); }); });
Also I added into the master page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
It is not working.When I debugging this Javascript function on the Chrome I saw an error:Uncaught Reference Error:PageMethods is not defined.
-
musefan over 10 yearsTry what? You have just posted part of the OP's code, which they already have
-
Tapas Mahata over 10 yearsNo, it's not the same. Keep a close look. ;)
-
musefan over 10 yearsOK, so you have made it
static
, how is that going to help? -
user2729114 over 10 yearsbecause I have to creating of this image in code behind into a method like this. return "<span style='color:red;font-size:12px;font-weight:bold;'>....</span><img style='width:112px; heigh:37px' src='...' class='clickme' />";
-
Tapas Mahata over 10 yearsThat could be a probable solution for the error "Uncaught Reference Error:PageMethods is not defined."
-
user2729114 over 10 yearsI can't using static because the page and some variable in the methods are not static.
-
musefan over 10 yearsThis won't fix that problem. The error shown is a javascript error, you wont fix that by making a code behind method static
-
Tapas Mahata over 10 years@user2729114 : Some common useful tips 1.The page method must have the System.Web.Services.WebMethod attribute. [WebMethod] 2.The page method must be public. [WebMethod] public ... 3.The page method must be static. [WebMethod] public static ... 4.The page method must be defined on the page (either inline or in the code-behind). It cannot be defined in a control, master page, or base page. 5.The ASP.NET AJAX Script Manager must have EnablePageMethods set to true.
-
musefan over 10 years@TapasMahata: If all that is true, then why don't you make that part of your answer. Then I will remove my downvote
-
Tapas Mahata over 10 years@musefan: please have a look on this similar post stackoverflow.com/questions/8188291/pagemethods-not-defined
-
musefan over 10 years@TapasMahata: Why? How does that make your answer any better?
-
Rich Hopkins over 8 yearsThanks so much! Very helpful, even two years later, almost to the day!