Compartir a través de


Administrar el historial del explorador con controles de servidor ASP.NET

Actualización: noviembre 2007

Como desarrollador de páginas, puede administrar entradas del historial del explorador y proporcionar una navegación lógica utilizando los controles de servidor ScriptManager y ScriptManagerProxy. El control de servidor ScriptManager permite establecer puntos del historial en la aplicación. Ambos controles permiten administrar la navegación que se produce cuando la página web se solicita a raíz de algún estado del historial.

Un punto del historial es un punto de la navegación lógica en la aplicación web que se puede representar a través de información de estado. La información de estado se puede utilizar para restaurar la aplicación web a un estado anterior, directamente con datos de estado o a través de un identificador de información de estado que está almacenada en otra parte.

Los puntos del historial se almacenan en la pila del historial del explorador únicamente como direcciones URL. El estado de historial se administra como datos en una cadena de consulta o como un valor de fragmento de dirección URL que se marca con el carácter "#". Debido a las restricciones de tamaño en direcciones URL, la información de estado que cree debe ser lo más pequeña posible. En el ejemplo siguiente se muestra una dirección URL que contiene suficientes datos de punto del historial para identificar el estado. Con esto, la aplicación puede volver a crear la página en ese estado.

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

Cuando un usuario hace clic en el botón Atrás, el explorador se desplaza por las direcciones URL vistas anteriormente, que incluyen direcciones URL con el estado del punto del historial. El código de cliente de la página web detecta que la dirección URL contiene datos de estado del historial y realiza una solicitud a la página, pasando la información de estado. Cuando la página procesa la solicitud, lee la información del estado de historial y activa una devolución (postback) de datos asincrónica. A continuación, los controles de servidor ScriptManagerProxy y ScriptManager provocan el evento Navigate. Puede controlar este evento y volver a crear la página como se requiera para la aplicación web.

Nota:

Para generar el código de ejemplo de este tema, debe tener Visual Studio 2008 Service Pack 1 o una versión posterior.

Sintaxis de ScriptManager y ScriptManagerProxy

En el ejemplo siguiente se muestra la sintaxis del control de servidor ScriptManager para trabajar con el historial del explorador.

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

Habilitar la administración del historial del explorador

Para utilizar la administración del historial, debe habilitarla a través del control de servidor ScriptManager. De forma predeterminada, la compatibilidad de historial no está habilitada. Cuando el historial está habilitado, se implementa de manera diferente en cada explorador. Con Internet Explorer, se representa un elemento iframe en el explorador, que puede producir una solicitud adicional al servidor. El modelo es, por consiguiente, de inclusión. En el ejemplo siguiente se muestra cómo habilitar mediante declaración el historial a través del control ScriptManager.

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

Crear puntos del historial del explorador

Para crear un punto del historial del explorador, se llama al método AddHistoryPoint del control ScriptManager. Este método permite definir el estado del servidor y las claves, así como los datos opcionales para representar el título de la entrada del historial en el explorador. Puede utilizar los datos de estado para volver a crear el estado de la página cuando se provoca un evento posterior de navegación del historial. Cuando se crea un punto del historial, los datos serializados y cifrados se anexan a la dirección URL de la página web de forma predeterminada. La dirección URL resultante se incluye en la pila del historial del explorador.

Nota:

Agregue los puntos del historial únicamente en respuesta a acciones del usuario, como hacer clic en una selección. Normalmente, los puntos del historial no se agregan únicamente a raíz de ejecutar código de aplicación.

En el siguiente ejemplo se utiliza el control UpdatePanel para habilitar las devoluciones (postbacks) de datos asincrónicas en la página. El control ScriptManager se utiliza para agregar los puntos del historial durante el controlador de eventos Click de los botones que activan estas devoluciones de datos asincrónicas. Al hacer clic en el botón Atrás del explorador, no abandona la página web sino que navega por los estados anteriores del historial de la página.

Ejecute un ejemplo de esta característica.

<%@ 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>

Administrar las solicitudes al servidor

Cuando el estado del servidor se detecta en una solicitud, se provoca el evento Navigate. Esto aparece como una devolución (postback) de datos asincrónica al servidor. Si tiene que determinar si la devolución de datos se produjo para la navegación o para algún otro propósito, lea la propiedad IsNavigating. Si esta propiedad está establecida en true, la devolución de datos se originó como una llamada de navegación.

En el ejemplo siguiente se muestra el control de servidor Wizard dentro de un control UpdatePanel. Esto hace que el control Wizard realice las devoluciones (postbacks) de datos asincrónicas cuando los usuarios navegan por el asistente. En el ejemplo, el código agrega los puntos del historial cuando se navega por los pasos del asistente.

Ejecute un ejemplo de esta característica.

<%@ 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>

Direcciones URL y estado del historial del servidor

Al crear un punto del historial, se decide qué información se almacena para el estado de dicho punto. Como mínimo, debe utilizar un par de clave/valor que identifique el estado en su aplicación. Podría decidir almacenar pares de clave/valor adicionales. Sin embargo, como esta información está almacenada en la dirección URL y la dirección URL tiene un límite de tamaño (tal y como lo determina el explorador), almacene sólo la información necesaria para volver a crear el estado.

En la dirección URL, la información de estado del servidor puede estar en un formulario con algoritmo hash aplicado o sin aplicar, dependiendo del valor que defina para la propiedad EnableHistory del control de servidor ScriptManager.

El estado del historial se delimita en la dirección URL con el carácter # (delimitador de fragmentos). La información del estado aparece tras el separador "&&", como se muestra en el ejemplo siguiente:

Default.aspx#&&s=Key+2

Al establecer EnableHistory en true, el fragmento de estado del historial se cifra antes de anexarse a la dirección URL de la página web. Esto mejora la seguridad y dificulta que un atacante cambie los datos de estado. Sin embargo, aunque se cifre la información, no almacene datos confidenciales en el campo de estado.

Observe que al aplicar un algoritmo hash a la información de estado, se crean direcciones URL que son largas e incluyen información que no es importante para el usuario.

Agregar títulos a los puntos del historial

El título de la página identifica normalmente las entradas en la pila del historial del explorador para esa entrada. Para ver un ejemplo, utilice la lista del historial de su explorador para ver los títulos de las últimas páginas que ha visitado. Normalmente puede ver la lista utilizando una lista desplegable en el cuadro de dirección URL.

Cuando se crea una entrada de punto de historial en una aplicación, de forma predeterminada el título de la página se utiliza para identificar la entrada. Si agrega varios puntos de historial a la misma página, de forma predeterminada todas las entradas tendrán el mismo título.

Sin embargo, puede proporcionar títulos significativos para entradas de historial individuales. En código de servidor, puede incluir información del título al crear un punto del historial llamando al método AddHistoryPoint.

En el ejemplo siguiente se muestra una variación del ejemplo anterior que incluye una entrada de título.

Ejecute un ejemplo de esta característica.

<%@ 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>

Vea también

Otros recursos

Administrar el historial del explorador