Ajax方法“类”是未定义的错误

AjaxMethod "Class" is undefined error

本文关键字:未定义 错误 方法 Ajax      更新时间:2023-09-26

我有一个旧的项目 asp.net,它使用Ajax.AjaxMethod()从Javascript调用服务器端代码。它以前工作正常(在我的意思是几年前),但现在它已经停止工作。

这是我的 C# 代码隐藏:

public partial class Signup : System.Web.UI.Page{
    protected void Page_Load(object sender, EventArgs e){
        Ajax.Utility.RegisterTypeForAjax(typeof(Signup));
    }
    [Ajax.AjaxMethod()]
    public DataTable fillStateDdl(int countryid)
    {
      objState = new MyClass.State();
      DataTable dtState = new DataTable();
      objState.CountryId = Convert.ToInt32(countryid);
      dtState = objState.GetStateCountry().Tables[0];
      return dtState;
    }
}

这是我的JavaScript代码:

function fillStates(countryid)
{
  var cntryid=countryid.options[countryid.selectedIndex].value;
  var response=Signup.fillStateDdl(cntryid);
  var states=response.value;
}

在javascript中,我收到"Microsoft JScript错误:'注册'未定义"错误消息。我在这里错过了什么吗?

最好把你的AjaxMethod分开。

public partial class Signup : System.Web.UI.Page{
    protected void Page_Load(object sender, EventArgs e){
        Ajax.Utility.RegisterTypeForAjax(typeof(YourAjaxClass));
    }
}
public class YourAjaxClass {
    [Ajax.AjaxMethod()]
    public DataTable fillStateDdl(int countryid)
    {
      objState = new MyClass.State();
      DataTable dtState = new DataTable();
      objState.CountryId = Convert.ToInt32(countryid);
      dtState = objState.GetStateCountry().Tables[0];
      return dtState;
    }
}

不能从 System.Web.Ui.Page 继承的 RegisterTypeForAjax 对象。这是行不通的。

然后你可以从javascript调用它。

function fillStates(countryid)
{
  var cntryid=countryid.options[countryid.selectedIndex].value;
  var response=YourAjaxClass.fillStateDdl(cntryid);
  var states=response.value;
}

我认为你缺少ajax的http处理程序。在 system.web 下的 web.config 中添加这些内容

<system.web>
<-- 
Other configuration

 -->
<httpHandlers>
      <add verb="POST,GET" path="*.ashx" type="Ajax.AjaxHandlerFactory,Ajax"/>
</httpHandlers>
</system.web>