我以前有一个.aspx.cs文件,其中包含许多WebMethods。它看起来像这样:
// webmethods.aspx.cs
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method1() {
}
[System.Web.Services.WebMethod]
public static string Method2() {
}
[System.Web.Services.WebMethod]
public static string Method3() {
}
}以及相应的.aspx文件,该文件如下所示:
<%@ Page Language="C#" MasterPageFile="Navigation.master" AutoEventWireup="true" CodeFile="webmethods.aspx.cs" Inherits="Default" Debug="true" %>然后,我能够使用AJAX成功地调用我的WebMethods。
但是webmethods.aspx.cs文件变得非常大,我想把WebMethods分成不同的文件。所以我就这样做了
webmethods.aspx.cs
// first file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method1() {
}
}webmethods2.aspx.cs
// second file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method2() {
}
}webmethods3.aspx
// third file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method3() {
}
}并将页面指令更改为Inherits="Foo.Default"。
但是现在,每当我试图通过AJAX访问其他文件中的任何WebMethods时,我都会得到一个Unknown WebMethod错误。AJAX请求仍被发送到webmethods.aspx.cs文件。
有人能帮我指出我做错了什么吗?
发布于 2018-12-04 04:30:49
WebForm编译模型允许为编译成单个.dll的partial class提供单个CodeBehind文件。App_code文件夹中的所有文件在编译.aspx和.aspx.cs之前也都在一个文件中编译。所以解决办法可能是这样的。
//Default.aspx
<!DOCTYPE html>
<%@ Page Language="C#" AutoEventWireup="true" Inherits="SomeApp.MyPage" %>
<%-- No CodeBehind. inherits external class--%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label><br />
<asp:Button runat="server" ID="btnTest" Text="click me" OnClick="btnTest_Click" />
</div>
</form>
</body>
</html>
//App_Code\MyPage.cs
namespace SomeApp
{
public partial class MyPage : System.Web.UI.Page
{
//You need to declare all page controls referred by code here
public System.Web.UI.WebControls.Label lblTest { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblTest.Text = "hello world from app_code";
}
}
}
}
//App_code\AnotherFile.cs
namespace SomeApp
{
public partial class MyPage : System.Web.UI.Page
{
protected void btnTest_Click(object sender, EventArgs e)
{
lblTest.Text = "hello world from btnTest_Click";
}
}
}它也应该与[WebMethod]一起工作。
https://stackoverflow.com/questions/53602893
复制相似问题