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

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定義形式:

 

 

<asp:ScriptManager ID="ScriptManager1" 

                   runat
="server">

      
<AuthenticationService Path="" />

      
<ProfileService LoadProperties="" Path="" />

      
<Scripts>

        
<asp:ScriptReference/>

      
</Scripts>

      
<Services>

        
<asp:ServiceReference />

      
</Services>

</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示例,在頁面中加入了日期控件和一個下拉框,根據下拉框選擇的不同,日期控件背景變爲不同的顏色。示例代碼如下:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<script runat="server">

    
void DropDownSelection_Change(Object sender, EventArgs e)

    
{

        Calendar1.DayStyle.BackColor 
=

            System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

    }


</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    
<title>ScriptManager Example</title>

</head>

<body>

    
<form id="form1" runat="server">

        
<div>

            
<asp:ScriptManager ID="ScriptManager1" 

                               runat
="server">

            
</asp:ScriptManager>

            
<asp:UpdatePanel ID="UpdatePanel1"

                             runat
="server">

                
<ContentTemplate>

                    
<asp:Calendar ID="Calendar1" 

                                  ShowTitle
="True"

                                  runat
="server" />

                    
<div>

                        Background:

                        
<br />

                        
<asp:DropDownList ID="ColorList" 

                                          AutoPostBack
="True" 

                                          OnSelectedIndexChanged
="DropDownSelection_Change"

                                          runat
="server">

                            
<asp:ListItem Selected="True" Value="White"> 

                            White 
</asp:ListItem>

                            
<asp:ListItem Value="Silver"> 

                            Silver 
</asp:ListItem>

                            
<asp:ListItem Value="DarkGray"> 

                            Dark Gray 
</asp:ListItem>

                            
<asp:ListItem Value="Khaki"> 

                            Khaki 
</asp:ListItem>

                            
<asp:ListItem Value="DarkKhaki"> D

                            ark Khaki 
</asp:ListItem>

                        
</asp:DropDownList>

                    
</div>

                
</ContentTemplate>

            
</asp:UpdatePanel>

            
<br />

        
</div>

    
</form>

</body>

</html>

 

三.客戶端腳本模式

在前面我們提到了ScriptMode屬性指定ScriptManager發送到客戶端的腳本的模式,它有四種模式:AutoInheritDebugRelease,默認值爲Auto

1Auto:它會根據Web站點的Web.config配置文件來決定使用哪一種模式,只有當配置文件中retail屬性設置爲false:Inherit:應該是通過程序設置ScriptMode的時候,等同於Auto?(不太瞭解)

<system.web>

  
<deployment retail="false" />

</system.web>

或者頁面中的Debug指令設爲true的時候會使用Debug版本,其他的情況都會使用Release版本。

<%@ Page Language="C#" Debug="true"

AutoEventWireup
="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

2

3Debug:客戶端腳本使用Debug版本,除非retail屬性設爲true

4Release:客戶端腳本使用Release版本,除非retail屬性設爲false

 

四.錯誤處理

在頁面回傳時如果發生了異常AsyncPostBackError事件將被觸發,錯誤信息的處理依賴於AllowCustomErrors屬性、AsyncPostBackErrorMessage屬性和Web.config中的<customErrors>配置區。下面看一個簡單的錯誤處理例子,在AsyncPostBackError事件中捕獲到異常信息並設置AsyncPostBackErrorMessage屬性。

 

<%@ Page Language="C#" %>

<script runat="server">

    protected 
void ErrorProcessClick_Handler(object sender, EventArgs e)

    
{
        
// This handler demonstrates an error condition. In this example

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

        
throw new ArgumentException();
    }


    protected 
void SuccessProcessClick_Handler(object sender, EventArgs e)

    
{
        
// This handler demonstrates no server side exception.

        UpdatePanelMessage.Text 
= "The asynchronous postback completed successfully.";

    }


    protected 
void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)

    
{
        ScriptManager1.AsyncPostBackErrorMessage 
= "異常信息爲:" + e.Exception.Message;

    }


</script>


<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    
<title>PageRequestManager endRequestEventArgs Example</title>

    
<style type="text/css">

    body 
{

        font-family
: Tahoma;

    
}


    #AlertDiv
{

    left
: 40%; top: 40%;

    position
: absolute; width: 200px;

    padding
: 12px; 

    border
: #000000 1px solid;

    background-color
: white; 

    text-align
: left;

    visibility
: hidden;

    z-index
: 99;

    
}


    #AlertButtons
{

    position
: absolute;

    right
: 5%;

    bottom
: 5%;

    
}


    
</style>

</head>

<body id="bodytag">

    
<form id="form1" runat="server">

        
<div>

            
<asp:ScriptManager ID="ScriptManager1" runat="server" 
            OnAsyncPostBackError
="ScriptManager1_AsyncPostBackError">

            
</asp:ScriptManager>
 
            
<script type="text/javascript" language="javascript">

                
var divElem = 'AlertDiv';

                
var messageElem = 'AlertMessage';

                
var errorMessageAdditional = 'Please try again.';

                
var bodyTag = 'bodytag';
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

                
function ToggleAlertDiv(visString)
                
{
                     
if (visString == 'hidden')

                     
{
                         $get(bodyTag).style.backgroundColor 
= 'white';                         
                     }

                     
else
                     
{
                         $get(bodyTag).style.backgroundColor 
= 'gray';                         

                     }


                     
var adiv = $get(divElem);

                     adiv.style.visibility 
= visString;

                }


                
function ClearErrorState() {

                     $get(messageElem).innerHTML 
= '';

                     ToggleAlertDiv('hidden');                     

                }

                
function EndRequestHandler(sender, args)

                
{
                   
if (args.get_error() != undefined && args.get_error().httpStatusCode == '500')
                   
{

                       
var errorMessage = args.get_error().message

                       args.set_errorHandled(
true);

                       ToggleAlertDiv('visible');

                       $get(messageElem).innerHTML 
= '"' + 

                                errorMessage + '
" ' + errorMessageAdditional;

                   }


                }


            
</script>

            
<asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">

                
<ContentTemplate>

                    
<asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">

                        
<asp:Label ID="UpdatePanelMessage" runat="server" />

                        
<br />

                        Last update:

                        
<%= DateTime.Now.ToString() %>

                        .

                        
<br />

                        
<asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"

                            OnClick
="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />

                        
<asp:Button runat="server" ID="Button2" Text="Submit Async Postback With Error"

                            OnClick
="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />

                        
<br />

                    
</asp:Panel>

                
</ContentTemplate>

            
</asp:UpdatePanel>

            
<div id="AlertDiv">

                
<div id="AlertMessage">

                
</div>

                
<br />

                
<div id="AlertButtons" >

                    
<input id="OKButton" type="button" value="OK" 

                           runat
="server" onclick="ClearErrorState()" />

                
</div>

           
</div>

    
</form>

</body>

</html>

運行後時界面:

發生異常信息:

 

五.Services屬性

Services用來管理對WebService的調用,通過<asp:ServiceReference>標籤可以在Services中註冊一個WebService,在運行時ScriptManager將爲每一個ServiceReference對象生成一個客戶端代理,<asp:ServiceReference>標籤一個很重要的屬性是Path,用來指定WebService的路徑,如下所示:

<asp:ScriptManager ID="SM1" runat="server">

    
<Services>

        
<asp:ServiceReference Path="Service.asmx"/>

    
</Services>

</asp:ScriptManager>

看一個簡單的調用WebService的例子:

WebService如下,注意在WebServiceSample上加ScriptService特性:頁面:

[ScriptService]

public class WebServiceSample : System.Web.Services.WebService {

    
public WebServiceSample()

    
{

        
//Uncomment the following line if using designed components 

        
//InitializeComponent(); 

    }



    [WebMethod]

    
public string EchoString(String s)

    
{
        
return "Hello " + s;
    }


}

ASPX

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    
<title>Untitled Page</title>

</head>

<script type="text/javascript" language="JavaScript">

    
function OnbuttonGo_click() 

    
{
        requestSimpleService 
= WebServiceSample.EchoString(

            document.getElementById('inputName').value,       
//params

            OnRequestComplete    
//Complete event

            );

        
return false;
    }


    
function OnRequestComplete(result) 

    
{
        alert(result);
    }


</script>

<body>

    
<form id="form1" runat="server">

    
<asp:ScriptManager ID="ScriptManager1" runat="server">

        
<Services>

            
<asp:ServiceReference Path="WebServiceSample.asmx"/>

        
</Services>

    
</asp:ScriptManager>

    
<div>

        
<input type="text" id="inputName" size=20/>

        
<input id="button" type="button" value="調 用" onclick="return OnbuttonGo_click()" /></div>

    
</form>

</body>

</html>

運行後效果如下:

當然了也可以在運行時動態的在Services中加入ServiceReference,下面看一個運行時動態加入ServiceReference的例子:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<script runat="server">

    
void Page_Load(object sender, EventArgs e)

    
{

        ServiceReference sr 
= new ServiceReference();

        sr.Path 
= "WebServiceSample.asmx";

        ScriptManager1.Services.Add(sr);

    }


</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    
<title>Untitled Page</title>

</head>

<script type="text/javascript" language="JavaScript">

    
function OnbuttonGo_click() 

    
{

        requestSimpleService 
= WebServiceSample.EchoString(

            document.getElementById('inputName').value,       
//params

            OnRequestComplete    
//Complete event

            );

        
return false;

    }


 

    
function OnRequestComplete(result) 

    
{

        alert(result);

    }


</script>

 

<body>

    

    
<form id="form1" runat="server">

    
<asp:ScriptManager ID="ScriptManager1" runat="server">

    
</asp:ScriptManager>

    
<div>

        
<input type="text" id="inputName" size=20/>

        
<input id="button" type="button" value="調 用" onclick="return OnbuttonGo_click()" /></div>

    
</form>

</body>

</html>

可以看到運行後和在ScriptManager中直接加入的效果是一樣的。

 

六.Scripts屬性

關於Scripts屬性到後面具體再說吧,最主要的屬性有Path指定腳本的路徑,ScriptMode指定客戶端腳本的模式,它會覆蓋ScriptManager中的ScriptMode屬性,還有一個屬性是IgnoreScriptPath,指定是否忽略掉ScriptManager中的ScriptPath屬性。

關於ScriptManager控件就學習到這裏了,至於AuthenticationService屬性和ProfileService屬性都很簡單。

示例代碼下載:http://files.cnblogs.com/Terrylee/ASPNETAJAXScriptManagerDemo.rar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章