为什么ajax调用不调用静态Web方法?

时间:2015-01-20 08:01:25

标签: javascript c# jquery ajax webmethod

我正在调用一个静态Web方法,该方法是用aspx.cs文件编写的,该文件有两个公共类:

public class Employee
{
    public string EmployeeNumber;
    public string FullName;
    public string LoginName;
    public string EmailID;
    public string Phone;
}

public partial class CustomWebMethods : LayoutsPageBase
{
    [WebMethod]
    public static List<Employee> GetEmployeeDetails(string employeeLoginName)
    {
        List<Employee> lstEmployeeDetail = new List<Employee>();
        //do something
        return lstEmployeeDetail;
    }
}

如果我将公共级员工保留在同一页面,那么ajax调用工作正常。

但是如果我将员工移动到另一个类库项目并添加该项目的引用,则ajax调用不起作用。为什么呢?

Javascript方法根本无法调用Web方法。

1 个答案:

答案 0 :(得分:1)

这是因为WebMethod属性内部工作原因。当您使用此属性标记某个方法时,它将通过PageName.aspx/MethodName网址提供。

然后,在将此方法移动到外部库之后,您也将其从页面方法中移出,之后它就不可用了。

因此,如果您想重构代码,则必须将WebService添加到项目中,您可以从该类调用其他库中的方法。

您还可以在客户端上创建一个javascript代理,如下所示:

<asp:ServiceReference InlineScript="true" Path="~/CustomersService.asmx"/>

或者使用ScriptManager,如下所示:

<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />

之后你可以use this proxy instead of ajax call

<script type="text/javascript">
function Add()
{
   var x = $get("txtX").value;
   var y = $get("txtY").value;
   PageMethods.Add(x, y, OnWSAdd);
}

function OnWSAdd(result)
{
   $get("spanAddResult").innerHTML += result;
}
</script>

Old, but great article about Understanding ASP.NET AJAX Web Services.