ASP.NET AJAX入门系列(2):使用ScriptManager控件

技术小甜 2017-11-16

path ajax Server 脚本 c# asp form html type WebService



ScriptManager控件包括在ASP.NET 2.0 AJAX Extensions中,它用来处理页面上的所有组件以及页面局部更新,生成相关的客户端代理脚本以便能够在JavaScript中访问Web Service,所有需要支持ASP.NET AJAXASP.NET页面上有且只能有一个ScriptManager控件。在ScriptManager控件中我们可以指定需要的脚本库,或者指定通过JS来调用的Web Service,以及调用AuthenticationServiceProfileService,还有页面错误处理等。

 
主要内容
1.控件概述
2.一个简单的示例
3.客户端脚本模式
4.错误处理
5Services属性
6Scripts属性
 
一.控件概述
ScriptManager控件包括在ASP.NET 2.0 AJAX Extensions中,它用来处理页面上的所有组件以及页面局部更新,生成相关的客户端代理脚本以便能够在JavaScript中访问Web Service,所有需要支持ASP.NET AJAXASP.NET页面上有且只能有一个ScriptManager控件。在ScriptManager控件中我们可以指定需要的脚本库,或者指定通过JS来调用的Web Service,还可以指定页面错误处理等。
使用<asp:ScriptManager/>来定义一个ScriptManager,简单的ScriptManager定义形式:
None.gif<asp:ScriptManager ID="ScriptManager1" 
None.gif
None.gif                   runat
="server">
None.gif
None.gif      
<AuthenticationService Path="" />
None.gif
None.gif      
<ProfileService LoadProperties="" Path="" />
None.gif
ExpandedBlockStart.gif      
<Scripts>
InBlock.gif
InBlock.gif        
<asp:ScriptReference/>
InBlock.gif
ExpandedBlockEnd.gif      
</Scripts>
None.gif
None.gif      
<Services>
None.gif
None.gif        
<asp:ServiceReference />
None.gif
None.gif      
</Services>
None.gif
None.gif
</asp:ScriptManager>
ScriptManager属性和方法如下:
 
属性/方法
描述
AllowCustomError
Web.config中的自定义错误配置区<customErrors>相联系,是否使用它,默认值为true
AsyncPostBackErrorMessage
异步回传发生错误时的自定义提示错误信息,
AsyncPostBackTimeout
异步回传时超时限制,默认值为90,单位为秒
EnablePartialRendering
是否支持页面的局部更新,默认值为True,一般不需要修改
ScriptMode
指定ScriptManager发送到客户端的脚本的模式,有四种模式:AutoInheritDebugRelease,默认值为Auto,后面会仔细说到。
ScriptPath
设置所有的脚本块的根目录,作为全局属性,包括自定义的脚本块或者引用第三方的脚本块。如果在Scripts中的<asp:ScriptReference/>标签中设置了Path属性,它将覆盖该属性。
OnAsyncPostBackError
异步回传发生异常时的服务端处理函数,在这里可以捕获一场信息并作相应的处理。
OnResolveScriptReference
指定ResolveScriptReference事件的服务器端处理函数,在该函数中可以修改某一条脚本的相关信息如路径、版本等。
 
二.一个简单的示例
这个例子其实是UpdatePanel示例,在页面中加入了日期控件和一个下拉框,根据下拉框选择的不同,日期控件背景变为不同的颜色。示例代码如下:
ExpandedBlockStart.gif<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
None.gif
None.gif 
None.gif
ExpandedBlockStart.gif
<script runat="server">
InBlock.gif
InBlock.gif    
void DropDownSelection_Change(Object sender, EventArgs e)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif
InBlock.gif        Calendar1.DayStyle.BackColor 
=
InBlock.gif
InBlock.gif            System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif
None.gif
</script>
None.gif
None.gif 
None.gif
None.gif
<html xmlns="http://www.w3.org/1999/xhtml">
None.gif
None.gif
<head id="Head1" runat="server">
None.gif
None.gif    
<title>ScriptManager Example</title>
None.gif
None.gif
</head>
None.gif
None.gif
<body>
None.gif
None.gif    
<form id="form1" runat="server">
None.gif
None.gif        
<div>
None.gif
None.gif            
<asp:ScriptManager ID="ScriptManager1" 
None.gif
None.gif                               runat
="server">
None.gif
None.gif            
</asp:ScriptManager>
None.gif
None.gif            
<asp:UpdatePanel ID="UpdatePanel1"
None.gif
None.gif                             runat
="server">
None.gif
None.gif                
<ContentTemplate>
None.gif
None.gif                    
<asp:Calendar ID="Calendar1" 
None.gif
None.gif                                  ShowTitle
="True"
None.gif
None.gif                                  runat
="server" />
None.gif
None.gif                    
<div>
None.gif
None.gif                        Background:
None.gif
None.gif                        
<br />
None.gif
None.gif                        
<asp:DropDownList ID="ColorList" 
None.gif
None.gif                                          AutoPostBack
="True" 
None.gif
None.gif                                          OnSelectedIndexChanged
="DropDownSelection_Change"
None.gif
None.gif                                          runat
="server">
None.gif
None.gif                            
<asp:ListItem Selected="True" Value="White"> 
None.gif
None.gif                            White 
</asp:ListItem>
None.gif
None.gif                            
<asp:ListItem Value="Silver"> 
None.gif
None.gif                            Silver 
</asp:ListItem>
None.gif
None.gif                            
<asp:ListItem Value="DarkGray"> 
None.gif
None.gif                            Dark Gray 
</asp:ListItem>
None.gif
None.gif                            
<asp:ListItem Value="Khaki"> 
None.gif
None.gif                            Khaki 
</asp:ListItem>
None.gif
None.gif                            
<asp:ListItem Value="DarkKhaki"> D
None.gif
None.gif                            ark Khaki 
</asp:ListItem>
None.gif
None.gif                        
</asp:DropDownList>
None.gif
None.gif                    
</div>
None.gif
None.gif                
</ContentTemplate>
None.gif
None.gif            
</asp:UpdatePanel>
None.gif
None.gif            
<br />
None.gif
None.gif        
</div>
None.gif
None.gif    
</form>
None.gif
None.gif
</body>
None.gif
None.gif
</html>
 
三.客户端脚本模式
在前面我们提到了ScriptMode属性指定ScriptManager发送到客户端的脚本的模式,它有四种模式:AutoInheritDebugRelease,默认值为Auto
1Auto:它会根据Web站点的Web.config配置文件来决定使用哪一种模式,只有当配置文件中retail属性设置为false:
None.gif<system.web>
None.gif
None.gif  
<deployment retail="false" />
None.gif
None.gif
</system.web>
或者页面中的Debug指令设为true的时候会使用Debug版本,其他的情况都会使用Release版本。
None.gif<%@ Page Language="C#" Debug="true"
None.gif
None.gifAutoEventWireup
="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2Inherit:应该是通过程序设置ScriptMode的时候,等同于Auto?(不太了解)
3Debug:客户端脚本使用Debug版本,除非retail属性设为true
4Release:客户端脚本使用Release版本,除非retail属性设为false
 
四.错误处理
在页面回传时如果发生了异常AsyncPostBackError事件将被触发,错误信息的处理依赖于AllowCustomErrors属性、AsyncPostBackErrorMessage属性和Web.config中的<customErrors>配置区。下面看一个简单的错误处理例子,在AsyncPostBackError事件中捕获到异常信息并设置AsyncPostBackErrorMessage属性。
ExpandedBlockStart.gif<%@ Page Language="C#" %>
None.gif
ExpandedBlockStart.gif
<script runat="server">
InBlock.gif
InBlock.gif    protected 
void ErrorProcessClick_Handler(object sender, EventArgs e)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        
// This handler demonstrates an error condition. In this example
InBlock.gif

InBlock.gif        
// the server error gets intercepted on the client and an alert is shown. 
InBlock.gif

InBlock.gif        
throw new ArgumentException();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    protected 
void SuccessProcessClick_Handler(object sender, EventArgs e)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        
// This handler demonstrates no server side exception.
InBlock.gif

InBlock.gif        UpdatePanelMessage.Text 
= "The asynchronous postback completed successfully.";
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    protected 
void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        ScriptManager1.AsyncPostBackErrorMessage 
= "异常信息为:" + e.Exception.Message;
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif
None.gif
</script>
None.gif
None.gif
None.gif
<html xmlns="http://www.w3.org/1999/xhtml">
None.gif
None.gif
<head id="Head1" runat="server">
None.gif
None.gif    
<title>PageRequestManager endRequestEventArgs Example</title>
None.gif
ExpandedBlockStart.gif    
<style type="text/css">
InBlock.gif
ExpandedSubBlockStart.gif    body 
{
InBlock.gif
InBlock.gif        font-family
: Tahoma;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

InBlock.gif
ExpandedSubBlockStart.gif    #AlertDiv
{
InBlock.gif
InBlock.gif    left
: 40%; top: 40%;
InBlock.gif
InBlock.gif    position
: absolute; width: 200px;
InBlock.gif
InBlock.gif    padding
: 12px; 
InBlock.gif
InBlock.gif    border
: #000000 1px solid;
InBlock.gif
InBlock.gif    background-color
: white; 
InBlock.gif
InBlock.gif    text-align
: left;
InBlock.gif
InBlock.gif    visibility
: hidden;
InBlock.gif
InBlock.gif    z-index
: 99;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

InBlock.gif
ExpandedSubBlockStart.gif    #AlertButtons
{
InBlock.gif
InBlock.gif    position
: absolute;
InBlock.gif
InBlock.gif    right
: 5%;
InBlock.gif
InBlock.gif    bottom
: 5%;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

InBlock.gif
ExpandedBlockEnd.gif    
</style>
None.gif
None.gif
</head>
None.gif
None.gif
<body id="bodytag">
None.gif
None.gif    
<form id="form1" runat="server">
None.gif
None.gif        
<div>
None.gif
None.gif            
<asp:ScriptManager ID="ScriptManager1" runat="server" 
None.gif            OnAsyncPostBackError
="ScriptManager1_AsyncPostBackError">
None.gif
None.gif            
</asp:ScriptManager>
None.gif 
ExpandedBlockStart.gif            
<script type="text/javascript" language="javascript">
InBlock.gif
InBlock.gif                
var divElem = 'AlertDiv';
InBlock.gif
InBlock.gif                
var messageElem = 'AlertMessage';
InBlock.gif
InBlock.gif                
var errorMessageAdditional = 'Please try again.';
InBlock.gif
InBlock.gif                
var bodyTag = 'bodytag';
InBlock.gif                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
InBlock.gif
InBlock.gif                
function ToggleAlertDiv(visString)
ExpandedSubBlockStart.gif                
{
InBlock.gif                     
if (visString == 'hidden')
InBlock.gif
ExpandedSubBlockStart.gif                     
{
InBlock.gif                         $get(bodyTag).style.backgroundColor 
= 'white';                         
ExpandedSubBlockEnd.gif                     }

InBlock.gif                     
else
ExpandedSubBlockStart.gif                     
{
InBlock.gif                         $get(bodyTag).style.backgroundColor 
= 'gray';                         
InBlock.gif
ExpandedSubBlockEnd.gif                     }

InBlock.gif
InBlock.gif                     
var adiv = $get(divElem);
InBlock.gif
InBlock.gif                     adiv.style.visibility 
= visString;
InBlock.gif
ExpandedSubBlockEnd.gif                }

InBlock.gif
ExpandedSubBlockStart.gif                
function ClearErrorState() {
InBlock.gif
InBlock.gif                     $get(messageElem).innerHTML 
= '';
InBlock.gif
InBlock.gif                     ToggleAlertDiv('hidden');                     
InBlock.gif
ExpandedSubBlockEnd.gif                }

InBlock.gif                
function EndRequestHandler(sender, args)
InBlock.gif
ExpandedSubBlockStart.gif                
{
InBlock.gif                   
if (args.get_error() != undefined && args.get_error().httpStatusCode == '500')
ExpandedSubBlockStart.gif                   
{
InBlock.gif
InBlock.gif                       
var errorMessage = args.get_error().message
InBlock.gif
InBlock.gif                       args.set_errorHandled(
true);
InBlock.gif
InBlock.gif                       ToggleAlertDiv('visible');
InBlock.gif
InBlock.gif                       $get(messageElem).innerHTML 
= '"' + 
InBlock.gif
InBlock.gif                                errorMessage + '
" ' + errorMessageAdditional;
InBlock.gif
ExpandedSubBlockEnd.gif                   }

InBlock.gif
ExpandedSubBlockEnd.gif                }

InBlock.gif
ExpandedBlockEnd.gif            
</script>
None.gif
None.gif            
<asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">
None.gif
None.gif                
<ContentTemplate>
None.gif
None.gif                    
<asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
None.gif
None.gif                        
<asp:Label ID="UpdatePanelMessage" runat="server" />
None.gif
None.gif                        
<br />
None.gif
None.gif                        Last update:
None.gif
None.gif                        
<%= DateTime.Now.ToString() %>
None.gif
None.gif                        .
None.gif
None.gif                        
<br />
None.gif
None.gif                        
<asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"
None.gif
None.gif                            OnClick
="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
None.gif
None.gif                        
<asp:Button runat="server" ID="Button2" Text="Submit Async Postback With Error"
None.gif
None.gif                            OnClick
="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />
None.gif
None.gif                        
<br />
None.gif
None.gif                    
</asp:Panel>
None.gif
None.gif                
</ContentTemplate>
None.gif
None.gif            
</asp:UpdatePanel>
None.gif
None.gif            
<div id="AlertDiv">
None.gif
None.gif                
<div id="AlertMessage">
None.gif
None.gif                
</div>
None.gif
None.gif                
<br />
None.gif
None.gif                
<div id="AlertButtons" >
None.gif
None.gif                    
<input id="OKButton" type="button" value="OK" 
None.gif
None.gif                           runat
="server" onclick="ClearErrorState()" />
None.gif
None.gif                
</div>
None.gif
None.gif           
</div>
None.gif
None.gif    
</form>
None.gif
None.gif
</body>
None.gif
None.gif
</html>
运行后时界面:
发生异常信息:
 
五.Services属性
Services用来管理对WebService的调用,通过<asp:ServiceReference>标签可以在Services中注册一个WebService,在运行时ScriptManager将为每一个ServiceReference对象生成一个客户端代理,<asp:ServiceReference>标签一个很重要的属性是Path,用来指定WebService的路径,如下所示:
None.gif<asp:ScriptManager ID="SM1" runat="server">
None.gif
None.gif    
<Services>
None.gif
None.gif        
<asp:ServiceReference Path="Service.asmx"/>
None.gif
None.gif    
</Services>
None.gif
None.gif
</asp:ScriptManager>
看一个简单的调用WebService的例子:
WebService如下,注意在WebServiceSample上加ScriptService特性:
None.gif[ScriptService]
None.gif
ExpandedBlockStart.gif
public class WebServiceSample : System.Web.Services.WebService {
InBlock.gif
InBlock.gif    
public WebServiceSample()
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif
InBlock.gif        
//Uncomment the following line if using designed components 
InBlock.gif
InBlock.gif        
//InitializeComponent(); 
InBlock.gif

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif
InBlock.gif    [WebMethod]
InBlock.gif
InBlock.gif    
public string EchoString(String s)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        
return "Hello " + s;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}
ASPX页面:
ExpandedBlockStart.gif<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
None.gif
None.gif
<html xmlns="http://www.w3.org/1999/xhtml" >
None.gif
None.gif
<head runat="server">
None.gif
None.gif    
<title>Untitled Page</title>
None.gif
None.gif
</head>
None.gif
ExpandedBlockStart.gif
<script type="text/javascript" language="JavaScript">
InBlock.gif
InBlock.gif    
function OnbuttonGo_click() 
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        requestSimpleService 
= WebServiceSample.EchoString(
InBlock.gif
InBlock.gif            document.getElementById('inputName').value,       
//params
InBlock.gif

InBlock.gif            OnRequestComplete    
//Complete event
InBlock.gif

InBlock.gif            );
InBlock.gif
InBlock.gif        
return false;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
function OnRequestComplete(result) 
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        alert(result);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif
None.gif
</script>
None.gif
None.gif
<body>
None.gif
None.gif    
<form id="form1" runat="server">
None.gif
None.gif    
<asp:ScriptManager ID="ScriptManager1" runat="server">
None.gif
None.gif        
<Services>
None.gif
None.gif            
<asp:ServiceReference Path="WebServiceSample.asmx"/>
None.gif
None.gif        
</Services>
None.gif
None.gif    
</asp:ScriptManager>
None.gif
None.gif    
<div>
None.gif
None.gif        
<input type="text" id="inputName" size=20/>
None.gif
None.gif        
<input id="button" type="button" value="调 用" onclick="return OnbuttonGo_click()" /></div>
None.gif
None.gif    
</form>
None.gif
None.gif
</body>
None.gif
None.gif
</html>
运行后效果如下:
当然了也可以在运行时动态的在Services中加入ServiceReference,下面看一个运行时动态加入ServiceReference的例子:
ExpandedBlockStart.gif<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
None.gif
ExpandedBlockStart.gif
<script runat="server">
InBlock.gif
InBlock.gif    
void Page_Load(object sender, EventArgs e)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif
InBlock.gif        ServiceReference sr 
= new ServiceReference();
InBlock.gif
InBlock.gif        sr.Path 
= "WebServiceSample.asmx";
InBlock.gif
InBlock.gif        ScriptManager1.Services.Add(sr);
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif
None.gif
</script>
None.gif
None.gif
<html xmlns="http://www.w3.org/1999/xhtml" >
None.gif
None.gif
<head runat="server">
None.gif
None.gif    
<title>Untitled Page</title>
None.gif
None.gif
</head>
None.gif
ExpandedBlockStart.gif
<script type="text/javascript" language="JavaScript">
InBlock.gif
InBlock.gif    
function OnbuttonGo_click() 
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif
InBlock.gif        requestSimpleService 
= WebServiceSample.EchoString(
InBlock.gif
InBlock.gif            document.getElementById('inputName').value,       
//params
InBlock.gif

InBlock.gif            OnRequestComplete    
//Complete event
InBlock.gif

InBlock.gif            );
InBlock.gif
InBlock.gif        
return false;
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
InBlock.gif
InBlock.gif    
function OnRequestComplete(result) 
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif
InBlock.gif        alert(result);
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif
None.gif
</script>
None.gif
None.gif 
None.gif
None.gif
<body>
None.gif
None.gif    
None.gif
None.gif    
<form id="form1" runat="server">
None.gif
None.gif    
<asp:ScriptManager ID="ScriptManager1" runat="server">
None.gif
None.gif    
</asp:ScriptManager>
None.gif
None.gif    
<div>
None.gif
None.gif        
<input type="text" id="inputName" size=20/>
None.gif
None.gif        
<input id="button" type="button" value="调 用" onclick="return OnbuttonGo_click()" /></div>
None.gif
None.gif    
</form>
None.gif
None.gif
</body>
None.gif
None.gif
</html>
可以看到运行后和在ScriptManager中直接加入的效果是一样的。
 
六.Scripts属性
关于Scripts属性到后面具体再说吧,最主要的属性有Path指定脚本的路径,ScriptMode指定客户端脚本的模式,它会覆盖ScriptManager中的ScriptMode属性,还有一个属性是IgnoreScriptPath,指定是否忽略掉ScriptManager中的ScriptPath属性。
关于ScriptManager控件就学习到这里了,至于AuthenticationService属性和ProfileService属性都很简单。










本文转自lihuijun51CTO博客,原文链接: http://blog.51cto.com/terrylee/67708,如需转载请自行联系原作者

登录 后评论
下一篇
云栖号资讯小编
20010人浏览
2020-07-13
相关推荐
ASP.NET AJAX入门系列
1009人浏览
2017-11-15 19:03:00
0
0
0
954