I am using Visual Studio 2022 for a .NET 4.7.2 project.
I created a simple page to make use of web method it's not working for me. Even the breakpoint is not being hit in web method.
I get undefined as response.
Here is the code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="HouseRentalPortal.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true"/>
<div>
<button onclick="testmethod()">Test</button>
</div>
</form>
</body>
<script>
function testmethod() {
PageMethods.Test("Developer", onsuccess, onfail);
}
function onsuccess(res) {
alert(res.d);
}
function onfail(res) {
alert("error" + res);
}
</script>
</html>
Code-behind C# :
using System;
using System.Web.Services;
namespace HouseRentalPortal
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Test(string name)
{
return "Welcome "+ name;
}
}
}
I just need to use the web method response in client side
Ok, you need to check several things:
First, check in App_Start folder, that you comment out, or change this:
To
So, the redirect mode not really required if you have friendly URLs enabled, but you need to turn of that redirect mode.
Next up:
While a jQuery .ajax call should work, I find that page methods don't work UNLESS you turn off friendly URL's. However, you can "fix" this issue with this:
JavaScript:
So, just ensure above (JavaScript) line of code runs before using a Page Method.
Last but not least?
You MUST drop in a script manager to the web page, and you MUST add the enable page methods.
Hence this:
So, taking all of above into account:
You checked/set in App_Start folder the RouteConfig.cs, and disabled redirect mode.
Hence this:
You have a script manager on the page, right after form tag, and enabled Page methods.
And as noted, if friendly URLs are enabled, then you need this line of JavaScript code to run BEFORE you call the Page Method:
So, then this markup: