我正在将 Visual Studio 2022 用于 .NET 4.7.2 项目。
我创建了一个简单的页面来使用网络方法,但它不适合我。即使在 Web 方法中也没有命中断点。
我的响应未定义。
这是代码
<%@ 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>
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;
}
}
}
我只需要在客户端使用Web方法响应
好的,您需要检查几件事:
首先,检查您注释掉的 App_Start 文件夹,或更改此内容:
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
至
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Off; //<-- this
routes.EnableFriendlyUrls(settings);
}
因此,如果您启用了友好 URL,则实际上不需要重定向模式,但您需要关闭该重定向模式。
下一个:
虽然 jQuery .ajax 调用应该可以工作,但我发现页面方法不起作用,除非您关闭友好的 URL。但是,您可以通过以下方式“解决”此问题:
JavaScript:
PageMethods.set_path(PageMethods.get_path() + '.aspx');
因此,只需确保在使用 PageMethod 之前运行上面的(JavaScript)代码行即可。
最后但并非最不重要的一点?
您必须将脚本管理器放入网页,并且必须添加启用页面方法。
因此:
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server"
EnablePageMethods="true">
</asp:ScriptManager>
... rest of your page follows....
因此,考虑到以上所有因素:
您在 App_Start 文件夹中检查/设置了 RouteConfig.cs,并禁用了重定向模式。
因此:
settings.AutoRedirectMode = RedirectMode.Off; <--- this
页面上有一个脚本管理器,就在表单标记之后,并启用了页面方法。
<asp:ScriptManager ID="ScriptManager1"
runat="server"
EnablePageMethods="true">
</asp:ScriptManager>
如上所述,如果启用了友好 URL,那么您需要在调用 PageMethod 之前运行这行 JavaScript 代码:
PageMethods.set_path(PageMethods.get_path() + '.aspx');
那么,这个标记:
<input id="Button1" type="button" value="button"
onclick="testmethod();return false;" />
<script>
PageMethods.set_path(PageMethods.get_path() + '.aspx');
function testmethod() {
PageMethods.Test("Developer", onsuccess, onfail);
}
function onsuccess(result) {
alert(result);
}
function onfail(res, usercontext, methodname) {
alert("error" + res);
}
</script>