ASP.NET AJAX + WebService的应用和问题

之前一直在看AJAX的东西,主要是老赵的文章和视频,但是一直就没有真正的实战过,今天手头的项目终于可以用到了,但是在理论界和实际的时候却出现了很多很多的问题。
目标:实现ScriptManager+Javascript+WebService == AJAX效果
步骤:
1.建立模板页
2.添加内容也
3.拖入ScriptManager
4.在ScriptManager中添加WebService的地址
5.在内容也添加UpdatePanel控件
6.添加WebService页
7.编写WebService后台程序
8.在内容页编写客户端脚本
9.测试
通过上面这些步骤想来实现最终的AJAX效果,结果出现了很多的问题
开始正文了!QA开始
1
Q:模板页是好东西,但是他的出现也带来了一些问题,最明显的问题就是空间的ID不在那么容易的掌握,从原来的你输入什么就是什么,变成了一大长串的东西让你无法轻易的找到。
A:通过XXXX.ClientID来解决问题,例如<%=Button1.ClientID%>
2
Q:ScriptManager能否加入多个WebService的地址
A:通过测试是可以的:)

1 < asp:ScriptManager  ID ="ScriptManager1"  runat ="server" >
2    < Services >
3     < asp:ServiceReference  Path ="/WebService/Product.asmx"  InlineScript ="false"   />
4     < asp:ServiceReference  Path ="/WebService/PromotionZone.asmx"  InlineScript ="false"   />
5    </ Services >
6   </ asp:ScriptManager >
7



3
Q:UpdatePanel是否是必须的,记得在看教程的时候没有
A:如果只是通过Javascript+WebService 来实现的话,完全的可以不使用UpdatePanel,要我说UpdatePanel是无敌的懒人的控件,成本太大了,所以上面的步骤中有一步可以省略了
4
Q:为什么我的Javascript不能调用WebService
A:Javascript+WebService 这样的方式需要在WebService 中添加一些引用
using System.Web.Script.Services;
在WebService 类的上面再加上一个声明[ScriptService]
最后在WebService的方法上面加上[WebMethod]
总的来说就是下面这个样子

 1 using  System;
 2 using  System.Web;
 3 using  System.Collections;
 4 using  System.Web.Services;
 5 using  System.Web.Services.Protocols;
 6 using  System.Web.Script.Services;
 7 using  System.Data;
 8
 9 /// <summary>
10/// Product 的摘要说明
11/// </summary>

12 [WebService(Namespace  =   " http://tempuri.org/ " )]
13 [WebServiceBinding(ConformsTo  =  WsiProfiles.BasicProfile1_1)]
14 [ScriptService]
15 public   class  Product : System.Web.Services.WebService  {
16
17    public Product () {
18
19        //如果使用设计的组件,请取消注释以下行 
20        //InitializeComponent(); 
21    }

22
23    [WebMethod]
24    public string HelloWorld() {
25        return "Hello World";
26    }

27}

28
29


5
Q:客户端调用WebService时不管用结果还不知道错误,这个东西还真的不好调试,怎么办
A:用过Javascript来调用WebService的时候是没有办法看到错误的,所以就需要自己准备一个错误处理机制,这样可以方便的看出问题在哪里。至于不能调用WebService多半是类的名称不对造成的,要不就是WebService的路径不对,下面是一段错误处理机制,嘿嘿,这里需要感谢老赵

 

 1 // 声明所有的Product的错误处理都交给failedCallback方法
 2 Product.set_defaultFailedCallback(failedCallback);
 3   function  failedCallback(error)
 4   {
 5  var message = String.format(
 6   "Timeout: {0}/nMessage: {1}/nExceptionType: {2}/nStackTrace: {3}",
 7   error.get_timedOut(),
 8   error.get_message(),
 9   error.get_exceptionType(),
10   error.get_stackTrace());
11 
12  alert(message);
13 }



6
Q:复杂的数据类型报错,说什么A circular reference was detected while serializing an object of type 'System.Reflection.Module'.反正是看不懂,最后才知道原来是返回的数据类型太复杂了
A:简单的字符串太不好处理,还是希望能处理复杂的数据类型,至少也要一个DataTable吧,有办法,需要下载一个ASP.NET Futures,然后引用一个Microsoft.Web.Preview.dll的类,最后修改一下Web.Config文件,做好以上几点就可以返回复杂的数据类型了,然后通过点呀点的就可以处理结果了,看不懂的JSON表达式可以说拜拜了,哈哈

1 < jsonSerialization >
2      < converters >
3       < add  name ="DataSetConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"   />
4       < add  name ="DataRowConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"   />
5       < add  name ="DataTableConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"   />
6      </ converters >
7     </ jsonSerialization >


7
Q:也是最后的一个问题了,客户端脚本报错,找不到这个找不到那个的,反正是一堆错误,为啥呢
A:位置问题,不能再像以前那样写在Head里面了,最好是跟在调用Javascript的控件后面,虽然不好看,不过还是忍了吧

最后最后贴出来自己代码

MasterPage
############################################################################

 1
 2
 3
 4 <% @ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage"  %>
 5
 6 <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
 7
 8 < html  xmlns ="http://www.w3.org/1999/xhtml"   >
 9 < head  runat ="server" >
10      < title > 无标题页 </ title >
11      < link  href ="StyleSheet.css"  rel ="stylesheet"  type ="text/css"   />     
12 </ head >
13 < body >
14      < form  id ="form1"  runat ="server" >
15      < asp:ScriptManager  ID ="ScriptManager1"  runat ="server" >
16    < Services >
17     < asp:ServiceReference  Path ="/WebService/Product.asmx"  InlineScript ="false"   />
18     < asp:ServiceReference  Path ="/WebService/PromotionZone.asmx"  InlineScript ="false"   />
19    </ Services >
20   </ asp:ScriptManager >
21   < script  language ="javascript"  type ="text/javascript" >
22 Product.set_defaultFailedCallback(failedCallback);
23 PromotionZone.set_defaultFailedCallback(failedCallback);
24 function failedCallback(error)
25 {
26  var message = String.format(
27   "Timeout: {0}/nMessage: {1}/nExceptionType: {2}/nStackTrace: {3}",
28   error.get_timedOut(),
29   error.get_message(),
30   error.get_exceptionType(),
31   error.get_stackTrace());
32 
33  alert(message);
34 }

35 
</ script >
36      < div >
37          < asp:contentplaceholder  id ="ContentPlaceHolder1"  runat ="server" >
38             duohahawuwu
39          </ asp:contentplaceholder >
40      </ div >
41      </ form >
42 </ body >
43 </ html >
44
45

Test.aspx
############################################################################

 1
 2
 3
 4 <% @ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" Title="Untitled Page"  %>
 5
 6 <% @ register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1"  %>
 7 < asp:Content  ID ="Content1"  ContentPlaceHolderID ="ContentPlaceHolder1"  Runat ="Server" >
 8      < href ="javascript:void(0)"  onclick ="GoPre()" > 上一页 </ a >
 9     
10      < href ="javascript:void(0)"  onclick ="GoPage(1)" > 1 </ a >
11      < href ="javascript:void(0)"  onclick ="GoPage(2)" > 2 </ a >
12     
13      < href ="javascript:void(0)"  onclick ="GoNext()" > 下一页 </ a >
14     
15      < href ="javascript:void(0)"  onclick ="TwoWebService()" > Two WebService </ a >
16      < div  id ="div_result" >
17         
18      </ div >
19
20      < script  language ="javascript"  type ="text/javascript" >
21    
22    var PageIndex = 0;
23    function GoPre()
24    {
25        PageIndex--;
26        Product.GetPageContent(PageIndex,PageResult);
27    }

28    function GoPage(NewPageIndex)
29    {
30        PageIndex = NewPageIndex;
31        Product.GetPageContent(PageIndex,PageResult);
32    }

33    function GoNext()
34    {
35        PageIndex++;
36        Product.GetPageContent(PageIndex,PageResult);
37    }

38    function PageResult(result)
39    {
40        var sb = new Sys.StringBuilder();
41        sb.append("<table border=1>");
42        for(var i = 0;i < result.rows.length;i++)
43        {
44            sb.append(String.format("<tr><td>{0}</td><td>{1}</td></tr>",result.rows[i]["Test"],result.rows[i]["Value"]));
45        }

46        
47        sb.append("</table>");
48        
49        $get("div_result").innerHTML = sb.toString();
50    }

51    function TwoWebService()
52    {
53        PromotionZone.HelloWorld(TwoWebServiceResult)
54    }

55    function TwoWebServiceResult(result)
56    {
57        alert(result);
58    }

59    
</ script >
60 </ asp:Content >
61
62  
63
64

Product.asmx
############################################################################

 1 using  System;
 2 using  System.Web;
 3 using  System.Collections;
 4 using  System.Web.Services;
 5 using  System.Web.Services.Protocols;
 6
 7 using  System.Web.Script.Services;
 8 using  System.Data;
 9
10 /// <summary>
11/// Product 的摘要说明
12/// </summary>

13 [WebService(Namespace  =   " http://tempuri.org/ " )]
14 [WebServiceBinding(ConformsTo  =  WsiProfiles.BasicProfile1_1)]
15 [ScriptService]
16 public   class  Product : System.Web.Services.WebService  {
17
18    public Product () {
19
20        //如果使用设计的组件,请取消注释以下行 
21        //InitializeComponent(); 
22    }

23
24    [WebMethod]
25    public string HelloWorld() {
26        return "Hello World";
27    }

28
29    [WebMethod]
30    public DataTable GetPageContent(int PageIndex)
31    {
32        DataTable objDt = new DataTable();
33        objDt.Columns.Add("Test");
34        objDt.Columns.Add("Value");
35        if (PageIndex > 0)
36        {
37            for (int i = 0; i < PageIndex; i++)
38            {
39                DataRow objDr = objDt.NewRow();
40                objDr["Test"= i.ToString();
41                objDr["Value"= (i * i).ToString();
42                objDt.Rows.Add(objDr);
43            }

44        }

45
46        return objDt;
47    }

48    
49}

50
51  
52
53

Web.Config
############################################################################

  1 <? xml version="1.0" ?>
  2 < configuration >
  3    < configSections >
  4      < sectionGroup  name ="system.web.extensions"  type ="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" >
  5        < sectionGroup  name ="scripting"  type ="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" >
  6            < section  name ="scriptResourceHandler"  type ="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  requirePermission ="false"  allowDefinition ="MachineToApplication" />
  7          < sectionGroup  name ="webServices"  type ="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" >
  8            < section  name ="jsonSerialization"  type ="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  requirePermission ="false"  allowDefinition ="Everywhere"   />
  9            < section  name ="profileService"  type ="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  requirePermission ="false"  allowDefinition ="MachineToApplication"   />
 10            < section  name ="authenticationService"  type ="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  requirePermission ="false"  allowDefinition ="MachineToApplication"   />
 11          </ sectionGroup >
 12        </ sectionGroup >
 13      </ sectionGroup >
 14    </ configSections >
 15
 16    < system.web >
 17      < pages >
 18        < controls >
 19          < add  tagPrefix ="asp"  namespace ="System.Web.UI"  assembly ="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 20        </ controls >
 21      </ pages >
 22      <!--
 23           Set compilation debug="true" to insert debugging
 24           symbols into the compiled page. Because this
 25           affects performance, set this value to true only
 26           during development.
 27      -->
 28      < compilation  debug ="false" >
 29        < assemblies >
 30          < add  assembly ="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 31        </ assemblies >
 32      </ compilation >
 33
 34      < httpHandlers >
 35        < remove  verb ="*"  path ="*.asmx" />
 36        < add  verb ="*"  path ="*.asmx"  validate ="false"  type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 37        < add  verb ="*"  path ="*_AppService.axd"  validate ="false"  type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 38        < add  verb ="GET,HEAD"  path ="ScriptResource.axd"  type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  validate ="false" />
 39      </ httpHandlers >
 40
 41      < httpModules >
 42        < add  name ="ScriptModule"  type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 43      </ httpModules >
 44    </ system.web >
 45
 46    < system.web.extensions >
 47      < scripting >
 48        < webServices >
 49        <!--  Uncomment this line to customize maxJsonLength and add a custom converter  -->
 50        <!--
 51       <jsonSerialization maxJsonLength="500">
 52         <converters>
 53           <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
 54         </converters>
 55       </jsonSerialization>
 56     -->
 57     < jsonSerialization >
 58      < converters >
 59       < add  name ="DataSetConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"   />
 60       < add  name ="DataRowConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"   />
 61       < add  name ="DataTableConverter"  type ="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"   />
 62      </ converters >
 63     </ jsonSerialization >
 64
 65
 66     <!--  Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate.  -->
 67        <!--
 68         <authenticationService enabled="true" requireSSL = "true|false"/>
 69        -->
 70
 71        <!--  Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
 72            and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
 73            writeAccessProperties attributes.  -->
 74        <!--
 75       <profileService enabled="true"
 76                       readAccessProperties="propertyname1,propertyname2"
 77                       writeAccessProperties="propertyname1,propertyname2" />
 78        -->
 79        </ webServices >
 80        <!--
 81       <scriptResourceHandler enableCompression="true" enableCaching="true" />
 82        -->
 83      </ scripting >
 84    </ system.web.extensions >
 85
 86    < system.webServer >
 87      < validation  validateIntegratedModeConfiguration ="false" />
 88      < modules >
 89        < add  name ="ScriptModule"  preCondition ="integratedMode"  type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 90      </ modules >
 91      < handlers >
 92        < remove  name ="WebServiceHandlerFactory-Integrated"   />
 93        < add  name ="ScriptHandlerFactory"  verb ="*"  path ="*.asmx"  preCondition ="integratedMode"
 94            type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 95        < add  name ="ScriptHandlerFactoryAppServices"  verb ="*"  path ="*_AppService.axd"  preCondition ="integratedMode"
 96            type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 97        < add  name ="ScriptResource"  preCondition ="integratedMode"  verb ="GET,HEAD"  path ="ScriptResource.axd"  type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"   />
 98      </ handlers >
 99    </ system.webServer >
100 </ configuration >
101
102
103
104
105

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值