最近初学asp.net,在公司用VS2010维护别人的网站,用AjaxPro成功实现客户端从后台拿到数据显示到前台页面上。
回家后在家里,自己下了一个VS2013,搭建了环境,也想复现一下AjaxPro跟后台交互,结果花了4个小时,始终提示:'xxxx' 未定义。去网上找了很多答案,一一试过,全部无效。
第二天,把家里的代码拿到公司,经过2个小时的逐行代码排查,最终解决问题。这里把学习过程记录一下,也希望有跟我遇到一样问题的朋友,能够少走点弯路。
先说最终结论:
1、如果要用命名空间,必须每个地方都用。以下几个地方都要注明:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="myapp.WebForm1" %>
namespace myapp { ... }
AjaxPro.Utility.RegisterTypeForAjax(typeof(myapp.WebForm1));
alert(myapp.WebForm1.getName().value);
如果不用命名空间,就所有地方都不要用。有的加有的不加,最后就会提示WebForm1 未定义或者myapp 未定义
2、javascript代码必须放在 <form id="form1" runat="server">中, 否则提示WebForm1 未定义或者myapp 未定义
<form id="form1" runat="server">
<script type="text/javascript">
alert(myapp.WebForm1.getName().value);
</script>
</form>
3、网上说的最多的就是web.config的设置了,这里两个2,一定要写对,网上很多教程都是1的,现在下载的都是ajaxpro2.dll所以这个也会造成WebForm1 未定义或者myapp 未定义
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro2"/>
<add name="ajaxpro" verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro2"/>
</httpHandlers>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.0" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ajaxpro" verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</handlers>
</system.webServer>
</configuration>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxPro;
namespace myapp {
public partial class WebForm1 : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){
AjaxPro.Utility.RegisterTypeForAjax(typeof(myapp.WebForm1));
}
[AjaxPro.AjaxMethod]
public string getName(){
return "dawnspace";
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="myapp.WebForm1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
alert(myapp.WebForm1.getName().value);
</script>
</form>
</body>
</html>