Partilhar via


Gerenciamento de histórico do navegador usando controles de servidor ASP.NET

sistema autônomo desenvolvedor de página, você pode gerenciar entradas de histórico do navegador e fornecer navegação lógica, usando o ScriptManager e ScriptManagerProxy controles de servidor. The ScriptManager o controle de servidor permite conjunto pontos de histórico do aplicativo. Ambos sistema autônomo controles permitem lidar com a navegação ocorre quando a página da Web é solicitada sistema autônomo resultado de algum estado de histórico.

A ponto histórico é um ponto de lógica de navegação no aplicativo Web Web pode ser representado por meio das informações de estado.As informações de estado podem ser usadas restauração aplicativo Web Web em um estado anterior, seja diretamente com os dados de estado ou através de um identificador para as informações de estado são armazenados em outro lugar.

Pontos de histórico são armazenados na pilha de histórico do navegador apenas sistema autônomo URLs.Estado do histórico é gerenciado sistema autônomo dados em uma seqüência de caracteres de consulta ou sistema autônomo um valor de fragmento de URL é marcado com o caractere "#".Devido sistema autônomo restrições de dimensionar em URLs, sistema autônomo informações de estado que você criar devem ser o menor possível.O exemplo a seguir mostra uma URL que contém dados de ponto de histórico suficientes para identificar o estado.A partir disso, o aplicativo pode re-criar a página no estado em questão.

http://MySamples/Ajax/Default.aspx#&&state=2

Quando um usuário clica Fazer backup botão, o navegador passa por URLs exibido anteriormente, que inclui URLs que contêm o estado do ponto histórico.Código do cliente na página da Web detecta que o URL contém dados de estado de histórico e faz uma solicitação para a página, passando as informações de estado.Quando a página processa a solicitação, ele lê as informações de estado de histórico e dispara um postback assíncrono.The ScriptManager e ScriptManagerProxy controles de servidor, em seguida, aumentar a Navigate evento. Você pode tratar este evento e re-criar a página sistema autônomo necessário para seu aplicativo Web da Web.

Observação:

Para criar o código de exemplo neste tópico, você deve ter o Visual Studio 2008 serviço empacotar 1 ou posterior.

ScriptManager e ScriptManagerProxy controle sintaxe

O exemplo a seguir mostra a sintaxe do ScriptManager controle de servidor para trabalhar com o histórico do navegador.

<asp:ScriptManager  
    EnableHistory="true|false"
    EnableStateHash="true|false"
    OnNavigate="navigateEventhandlerName">
</asp:ScriptManager>

Habilitando o gerenciamento de histórico do navegador

Para usar o gerenciamento de histórico, habilite-através de ScriptManager controle de servidor. Por padrão, o suporte para histórico não está habilitado.Quando o histórico está habilitado, ele é implementado diferente para cada localizador.Para o Internet Explorer, um iframe elemento é processado no navegador, que pode causar uma solicitação adicional para o servidor. O modelo, portanto, é uma abordagem opt-in.O exemplo a seguir mostra como habilitar o histórico declarativamente por meio de ScriptManager controle.

<asp:ScriptManager  ID="ScriptManager1" 
    EnableHistory="true" />

Criando pontos de histórico do navegador

Para criar um ponto histórico do navegador, você chamar o AddHistoryPoint método para o ScriptManager controle. Esse método permite que você defina o estado do servidor e as chaves e dados opcionais para representar o título da entrada do histórico no navegador.Você pode usar os dados de estado para re-criar o estado da página quando um evento de navegação do histórico subseqüentes.Quando você criar um ponto histórico, por padrão serializado e dados criptografados são acrescentados à URL da página da Web.A URL resultante é incluída na pilha de histórico do navegador.

Observação:

Adicione pontos de histórico somente em resposta às ações do usuário, sistema autônomo clicar em uma seleção.Normalmente, sistema autônomo pontos de histórico não são adicionados sistema autônomo resultado, apenas de executar o código do aplicativo.

O exemplo a seguir utiliza o UpdatePanel controle para permitir que postbacks assíncrono na página. The ScriptManager o controle é usado para adicionar pontos de histórico durante o Click manipulador de eventos dos botões que disparem postbacks assíncrono. Quando você clica em Fazer backup botão, você não deixe a página da Web, mas em vez disso, navegar pelos estados de histórico anterior da página.

Executar um exemplo desse recurso.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    Private Shared key As String = "s"

    ' Handle the Navigate event
    Public Sub OnNavigateHistory(ByVal sender As Object, ByVal e As HistoryEventArgs)
        LabelHistoryData.Text = Server.HtmlEncode(e.State(key))
    End Sub

    ' On button click, handle the event and set a history point. 
    Public Sub ButtonClick(ByVal sender As Object, ByVal e As EventArgs)
        LabelHistoryData.Text = CType(sender, Button).Text
        ScriptManager.GetCurrent(Me).AddHistoryPoint(key, LabelHistoryData.Text)
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code>event.<br />
                    </li>
                </ol>
            </div>

            <p>
                In this example, three buttons outside the <code>UpdatePanel</code> control can
                trigger an asynchronous postback. You can see the results of the update through
                the date and time that renders in the Web page along with a value indicating the 
                button that triggered the partial refresh.</p>
            <p>
                When you press a button, the server-side <code>Click</code> event handler for the button 
                stores data and uses the data as a history point. If you click the browser's Back button, 
                you will see the state Web page return to a previous button value, representing the previous 
                button you pressed. However, you will see that the time within the Web page continues to be 
                incremented.
            </p>
            <p>To see the effect of this logic, do the following.</p>

            <ol>
                <li>Press <b>1</b>. See the panel refresh.</li>
                <li>Press <b>3</b>. See the panel refresh.</li>
                <li>Press <b>2</b>. See the panel refresh.</li>
                <li>Press the browser's Back button. Note that the panel is refreshed with previous
                    data, but the date and time are updated to current values.</li>
            </ol>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
                </Triggers>
                <ContentTemplate>
                    <asp:Panel  CssClass="box" ID="Content" Height="40px">
                        Date and Time:
                        <%= DateTime.Now.ToLongTimeString() %>
                        <br />
                        Page's refresh state:
                        <asp:Label  ID="LabelHistoryData" />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <p />
            <asp:Button  ID="Button1" Text="Key 1" OnClick="ButtonClick" />
            <asp:Button  ID="Button2" Text="Key 2" OnClick="ButtonClick" />
            <asp:Button  ID="Button3" Text="Key 3" OnClick="ButtonClick" />
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    private static String key = "s";

    // Handle the Navigate event
    public void OnNavigateHistory(object sender, HistoryEventArgs e) {
        LabelHistoryData.Text = Server.HtmlEncode(e.State[key]);
    }

    // On button click, handle the event and set a history point. 
    public void ButtonClick(object sender, EventArgs e) {
        LabelHistoryData.Text = ((Button)sender).Text;
        ScriptManager.GetCurrent(this).AddHistoryPoint(key, LabelHistoryData.Text);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code>event.<br />
                    </li>
                </ol>
            </div>

            <p>
                In this example, three buttons outside the <code>UpdatePanel</code> control can
                trigger an asynchronous postback. You can see the results of the update through
                the date and time that renders in the Web page along with a value indicating the 
                button that triggered the partial refresh.</p>
            <p>
                When you press a button, the server-side <code>Click</code> event handler for the button 
                stores data and uses the data as a history point. If you click the browser's Back button, 
                you will see the state Web page return to a previous button value, representing the previous 
                button you pressed. However, you will see that the time within the Web page continues to be 
                incremented.
            </p>
            <p>To see the effect of this logic, do the following.</p>

            <ol>
                <li>Press <b>1</b>. See the panel refresh.</li>
                <li>Press <b>3</b>. See the panel refresh.</li>
                <li>Press <b>2</b>. See the panel refresh.</li>
                <li>Press the browser's Back button. Note that the panel is refreshed with previous
                    data, but the date and time are updated to current values.</li>
            </ol>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
                </Triggers>
                <ContentTemplate>
                    <asp:Panel  CssClass="box" ID="Content" Height="40px">
                        Date and Time:
                        <%= DateTime.Now.ToLongTimeString() %>
                        <br />
                        Page's refresh state:
                        <asp:Label  ID="LabelHistoryData" />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <p />
            <asp:Button  ID="Button1" Text="Key 1" OnClick="ButtonClick" />
            <asp:Button  ID="Button2" Text="Key 2" OnClick="ButtonClick" />
            <asp:Button  ID="Button3" Text="Key 3" OnClick="ButtonClick" />
        </div>
    </form>
</body>
</html>

Tratamento de solicitações ao servidor

Quando o estado do servidor é detectado em uma solicitação, o Navigate evento é gerado. Isso aparece como um postback assíncrono para o servidor.Se você tiver que determinar se o postback ocorreu para navegação ou para algum Outros fim, você pode ler o IsNavigating propriedade. Se esta propriedade for definida sistema autônomo true, o postback criados sistema autônomo uma telefonar de navegação.

O exemplo a seguir mostra o Wizard controle de servidor dentro de um UpdatePanel controle. Isso faz com que o Wizard controle para executar postbacks assíncrono quando os usuários navegar no assistente. No exemplo de código adiciona pontos de histórico quando as etapas do assistente são navegadas.

Executar um exemplo desse recurso.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    Private Shared stepKey As String = "s"

    Protected Sub OnNavigateHistory(ByVal sender As Object, ByVal args As HistoryEventArgs)
        Dim stateString As String = args.State(stepKey)
        Dim [step] As Integer = If(stateString IsNot Nothing, Integer.Parse(stateString), 0)
        MachineConfiguratorWizard.ActiveStepIndex = [step]
    End Sub

    Protected Sub OnActiveStepChanged(ByVal sender As Object, ByVal e As EventArgs)
        If Not ScriptManager1.IsNavigating AndAlso IsPostBack Then
            Dim index As Integer = MachineConfiguratorWizard.ActiveStepIndex
            ScriptManager1.AddHistoryPoint(stepKey, index.ToString(), "Step " + (index + 1).ToString())
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <div>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code> event.
                    </li>
                    <li>Protecting the history code with <code>IsNavigating</code>
                    </li>
                </ol>
            </div>
        <p>
        In this example, the <code>Wizard</code> server control provides it's own navigation, but 
        as each step is selected a history point is added. In order to do this, a history point is only added if the page is not being refreshed beacuse of a history point.</p>
            <asp:UpdatePanel  ID="WizardPanel">
                <ContentTemplate>
                    <asp:Wizard ID="MachineConfiguratorWizard"  ActiveStepIndex="0" BackColor="#dddddd"
                        BorderWidth="10" CellPadding="10" CellSpacing="10" Height="200px" Width="700px"
                        FinishPreviousButtonText="<" StartNextButtonText=">" StepNextButtonText=">" StepPreviousButtonText="<"
                        FinishCompleteButtonText="<|>" OnActiveStepChanged="OnActiveStepChanged">
                        <WizardSteps>
                            <asp:WizardStep ID="Step1"  Title="Step 1">
                                <h2>
                                    STEP 1</h2>
                                <br />
                            </asp:WizardStep>
                            <asp:WizardStep ID="Step2"  Title="Step 2">
                                <h2>
                                    STEP 2</h2>
                                <br />
                            </asp:WizardStep>
                            <asp:WizardStep ID="Step3"  Title="Step 3">
                                <h2>
                                    STEP 3</h2>
                                <br />
                            </asp:WizardStep>
                        </WizardSteps>
                        <StepStyle Font-Names="tahoma" Font-Size="Smaller" VerticalAlign="Top" />
                        <SideBarStyle Font-Size="Small" VerticalAlign="Top" BackColor="#FFFFC0" Font-Names="tahoma" />
                        <FinishPreviousButtonStyle BackColor="White" BorderColor="Black" BorderWidth="3px"
                            Font-Names="Tahoma" Font-Size="Medium" />
                        <NavigationButtonStyle BackColor="White" BorderColor="Black" BorderStyle="Solid"
                            BorderWidth="3px" Font-Names="Tahoma" Font-Size="Medium" />
                        <FinishCompleteButtonStyle Font-Names="Tahoma" Font-Size="Medium" />
                    </asp:Wizard>
                </ContentTemplate>
            </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    private static readonly string stepKey = "s";

    protected void OnNavigateHistory(object sender, HistoryEventArgs args)
    {
        string stateString = args.State[stepKey];
        int step = (stateString != null) ? int.Parse(stateString) : 0;
        MachineConfiguratorWizard.ActiveStepIndex = step;
    }

    protected void OnActiveStepChanged(object sender, EventArgs e)
    {
        if (!ScriptManager1.IsNavigating && IsPostBack) {
            int index = MachineConfiguratorWizard.ActiveStepIndex;
            ScriptManager1.AddHistoryPoint(stepKey, index.ToString(), "Step " + (index+1).ToString());
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <div>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code> event.
                    </li>
                    <li>Protecting the history code with <code>IsNavigating</code>
                    </li>
                </ol>
            </div>
        <p>
        In this example, the <code>Wizard</code> server control provides it's own navigation, but 
        as each step is selected a history point is added. In order to do this, a history point is only added if the page is not being refreshed beacuse of a history point.</p>
            <asp:UpdatePanel  ID="WizardPanel">
                <ContentTemplate>
                    <asp:Wizard ID="MachineConfiguratorWizard"  ActiveStepIndex="0" BackColor="#dddddd"
                        BorderWidth="10" CellPadding="10" CellSpacing="10" Height="200px" Width="700px"
                        FinishPreviousButtonText="<" StartNextButtonText=">" StepNextButtonText=">" StepPreviousButtonText="<"
                        FinishCompleteButtonText="<|>" OnActiveStepChanged="OnActiveStepChanged">
                        <WizardSteps>
                            <asp:WizardStep ID="Step1"  Title="Step 1">
                                <h2>
                                    STEP 1</h2>
                                <br />
                            </asp:WizardStep>
                            <asp:WizardStep ID="Step2"  Title="Step 2">
                                <h2>
                                    STEP 2</h2>
                                <br />
                            </asp:WizardStep>
                            <asp:WizardStep ID="Step3"  Title="Step 3">
                                <h2>
                                    STEP 3</h2>
                                <br />
                            </asp:WizardStep>
                        </WizardSteps>
                        <StepStyle Font-Names="tahoma" Font-Size="Smaller" VerticalAlign="Top" />
                        <SideBarStyle Font-Size="Small" VerticalAlign="Top" BackColor="#FFFFC0" Font-Names="tahoma" />
                        <FinishPreviousButtonStyle BackColor="White" BorderColor="Black" BorderWidth="3px"
                            Font-Names="Tahoma" Font-Size="Medium" />
                        <NavigationButtonStyle BackColor="White" BorderColor="Black" BorderStyle="Solid"
                            BorderWidth="3px" Font-Names="Tahoma" Font-Size="Medium" />
                        <FinishCompleteButtonStyle Font-Names="Tahoma" Font-Size="Medium" />
                    </asp:Wizard>
                </ContentTemplate>
            </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

URLs e estado de histórico do servidor

Quando você cria um ponto histórico, você decide quais informações para armazenar o estado do ponto histórico.Mínimo, você deve usar um emparelhar chave/valor que identifica o estado para o seu aplicativo.Você pode decidir armazenar pares chave/valor adicional.No entanto, pois essa informações são armazenadas no URL e a URL tem um dimensionar de limite (conforme determinado pelo navegador), apenas sistema autônomo informações que você precisa de armazenamento na ordem a re-criar o estado.

No URL, as informações de estado do servidor podem ser em um formulário com hash ou formulário unhashed, dependendo a configuração que você define para o EnableHistory propriedade das ScriptManager controle de servidor.

Estado do histórico é delimitado no URL com o caractere # (delimitador fragmento).Segue sistema autônomo informações de estado de "&&" separador, conforme mostrado no exemplo a seguir:

Default.aspx#&&s=Key+2

Ao conjunto EnableHistory para true, o fragmento de estado de histórico é criptografado antes de ele é acrescentado à URL da página da Web. Isso melhora a segurança, tornando difícil para um invasor alterar os dados de estado.No entanto, mesmo que as informações são criptografadas, não armazene dados confidenciais no campo de estado.

Observe que as informações de estado de hash cria URLs que são longos e que inclua informações que não seja significativas para o usuário.

Adicionar títulos para pontos de histórico

Entradas na pilha de histórico do navegador geralmente são identificadas pelo título da página para essa entrada.Para ver um exemplo disso, use a lista do Histórico do navegador para exibir os títulos das páginas que você visitou recentemente.(Normalmente, você ver a lista usando uma lista suspensa na caixa Endereço de URL.)

Quando você criar uma entrada de ponto histórico em seu aplicativo, por padrão, o título da página é usado para identificar a entrada.Se você adicionar vários pontos de histórico da mesma página, por padrão todas as entradas terá o mesmo título.

No entanto, você pode fornecer títulos significativos para as entradas do histórico individuais.No código do servidor, você pode incluir informações de título quando você cria um ponto histórico, chamando o AddHistoryPoint método.

O exemplo a seguir mostra uma variação no exemplo anterior, incluindo uma entrada de título.

Executar um exemplo desse recurso.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    Private Shared key As String = "s"

    ' Handle the Navigate event
    Public Sub OnNavigateHistory(ByVal sender As Object, ByVal e As HistoryEventArgs)
        LabelHistoryData.Text = Server.HtmlEncode(e.State(key))
    End Sub

    ' On button click, handle the event and set a history point. 
    Public Sub ButtonClick(ByVal sender As Object, ByVal e As EventArgs)
        LabelHistoryData.Text = CType(sender, Button).Text
        ScriptManager.GetCurrent(Me).AddHistoryPoint(key, LabelHistoryData.Text, "Entry: " + LabelHistoryData.Text)
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code>event.<br />
                    </li>
                </ol>
            </div>

            <p>
                In this example, three buttons outside the <code>UpdatePanel</code> control can
                trigger an asynchronous postback. You can see the results of the update through
                the date and time that renders in the Web page along with a value indicating the 
                button that triggered the partial refresh.</p>
            <p>
                When you press a button, the server-side <code>Click</code> event handler for the button 
                stores data and uses the data as a history point. If you click the browser's Back button, 
                you will see the state Web page return to a previous button value, representing the previous 
                button you pressed. However, you will see that the time within the Web page continues to be 
                incremented.
            </p>
            <p>To see the effect of this logic, do the following.</p>

            <ol>
                <li>Press <b>1</b>. See the panel refresh.</li>
                <li>Press <b>3</b>. See the panel refresh.</li>
                <li>Press <b>2</b>. See the panel refresh.</li>
                <li>Press the browser's Back button. Note that the panel is refreshed with previous
                    data, but the date and time are updated to current values.</li>
            </ol>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
                </Triggers>
                <ContentTemplate>
                    <asp:Panel  CssClass="box" ID="Content" Height="40px">
                        Date and Time:
                        <%= DateTime.Now.ToLongTimeString() %>
                        <br />
                        Page's refresh state:
                        <asp:Label  ID="LabelHistoryData" />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <p />
            <asp:Button  ID="Button1" Text="Key 1" OnClick="ButtonClick" />
            <asp:Button  ID="Button2" Text="Key 2" OnClick="ButtonClick" />
            <asp:Button  ID="Button3" Text="Key 3" OnClick="ButtonClick" />
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >
    private static String key = "s";

    // Handle the Navigate event
    public void OnNavigateHistory(object sender, HistoryEventArgs e) {
        LabelHistoryData.Text = Server.HtmlEncode(e.State[key]);
    }

    // On button click, handle the event and set a history point. 
    public void ButtonClick(object sender, EventArgs e) {
        LabelHistoryData.Text = ((Button)sender).Text;
        ScriptManager.GetCurrent(this).AddHistoryPoint(key, LabelHistoryData.Text, "Entry: " + LabelHistoryData.Text);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
    <title>Microsoft ASP.NET 3.5 Extensions: Managing History</title>
    <link href="../../include/qsstyle.css" type="text/css" rel="Stylesheet" />
</head>
<body>
    <form id="form1" >
        <div>
            <asp:ScriptManager  ID="ScriptManager1" OnNavigate="OnNavigateHistory" 
                EnableHistory="true" EnableSecureHistoryState="false" />
            <h2>
                Microsoft ASP.NET 3.5 Extensions: Adding Server-side Browser History Points and Title Entries</h2>
            <p/>

            <div id="Div1" class="new">
                <p>This sample shows:</p>
                <ol>
                    <li>How to use the <code>ScriptManager</code> control to set a history point and add titles.</li>
                    <li>The <code>ScriptManager</code> control, the <code>EnableHistory</code> and 
                    <code>EnableSecureHistoryState</code> properties and 
                    the <code>OnNavigate</code> property to handle the <code>navigate</code>event.<br />
                    </li>
                </ol>
            </div>

            <p>
                In this example, three buttons outside the <code>UpdatePanel</code> control can
                trigger an asynchronous postback. You can see the results of the update through
                the date and time that renders in the Web page along with a value indicating the 
                button that triggered the partial refresh.</p>
            <p>
                When you press a button, the server-side <code>Click</code> event handler for the button 
                stores data and uses the data as a history point. If you click the browser's Back button, 
                you will see the state Web page return to a previous button value, representing the previous 
                button you pressed. However, you will see that the time within the Web page continues to be 
                incremented.
            </p>
            <p>To see the effect of this logic, do the following.</p>

            <ol>
                <li>Press <b>1</b>. See the panel refresh.</li>
                <li>Press <b>3</b>. See the panel refresh.</li>
                <li>Press <b>2</b>. See the panel refresh.</li>
                <li>Press the browser's Back button. Note that the panel is refreshed with previous
                    data, but the date and time are updated to current values.</li>
                <li>Press the browser's "Recent Pages" drop down menu and review the history entries and their titles.</li>
            </ol>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
                </Triggers>
                <ContentTemplate>
                    <asp:Panel  CssClass="box" ID="Content" Height="40px">
                        Date and Time:
                        <%= DateTime.Now.ToLongTimeString() %>
                        <br />
                        Page's refresh state:
                        <asp:Label  ID="LabelHistoryData" />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <p />
            <asp:Button  ID="Button1" Text="Key 1" OnClick="ButtonClick" />
            <asp:Button  ID="Button2" Text="Key 2" OnClick="ButtonClick" />
            <asp:Button  ID="Button3" Text="Key 3" OnClick="ButtonClick" />
        </div>
    </form>
</body>
</html>

Consulte também

Outros recursos

Gerenciamento de histórico do navegador