begin process at 2012 05 27 01:40:53
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

ASP.Net

 > STOCKER LE VIEWSTATE SUR LE SERVEUR PLUTÔT QUE LE CLIENT

STOCKER LE VIEWSTATE SUR LE SERVEUR PLUTÔT QUE LE CLIENT


 Information sur la source

Note :
10 / 10 - par 1 personne
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :ASP.Net Source .NET ( DotNet ) Classé sous :viewstate, loadpagestatefrompersistencemedium, savepagestatetopersistencemedium, serverviewstatepage Niveau :Débutant Date de création :25/11/2006 Date de mise à jour :26/12/2007 13:54:39 Vu :11 629

Auteur : jesusonline

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note


 Description

Par défaut ASP.net stocke le viewstate dans un champ caché du formulaire coté client, ce bout de code permet d'enregistrer cette valeur côté serveur dans une propriété static. Attention si l'application redemarre le viewstate sera alors perdu, j'ai posté ce code seulement pour montrer le concept, mais en production si vous avez vraiment besoin de stocker le viewstate sur le serveur plutot que le client (ce qui est très rare) il est conseille de l'enregistrer dans une base de donnée ou tout autre espace de stockage persistant. De plus comme je supprime le viewstate de la collection l'utilisateur risque de rencontrer des problèmes s'il joue avec le bouton retour et refait la même requête.  

La source récupere la valeur non sérializé du viewstate le stock sur le serveur avec un identifiant unique et écrit dans un champ caché seulement cet identifiant unique.

UPDATE : ASP.net fait ce comportement nativement avec le SessionPageStatePersister : http://msdn2.microsoft.com/en-us/library/system.we b.ui.sessionpagestatepersister.aspx

Source

  • using System;
  • using System.Data;
  • using System.Configuration;
  • using System.Collections;
  • using System.Web;
  • using System.Web.Security;
  • using System.Web.UI;
  • using System.Web.UI.WebControls;
  • using System.Collections.Generic;
  • /// <summary>
  • /// This class save the viewstate value of each request on the WebServer.
  • /// Don't use this on a server production ! If the application restart all the viewstates
  • /// information will be loosed. You should save the viewstate in a DataBase or in any persistent storage.
  • /// </summary>
  • public class ServerViewStatePage : Page
  • {
  • private static Object _lock = new object();
  • private static Dictionary<Guid, Object> __viewstates;
  • /// <summary>
  • /// Gets a dictionnary of viewstates stocked in the server.
  • /// </summary>
  • /// <value>The dictionary of viewstate stocked in the server.</value>
  • private static Dictionary<Guid, Object> _viewstates
  • {
  • get
  • {
  • lock (_lock)
  • {
  • if (__viewstates == null)
  • __viewstates = new Dictionary<Guid, Object>();
  • }
  • return __viewstates;
  • }
  • }
  • /// <summary>
  • /// Loads any saved view-state information to the <see cref="T:System.Web.UI.Page"></see> object.
  • /// </summary>
  • /// <returns>The saved view state.</returns>
  • /// <remarks>Try to get the original viewstate if the __VIEWSTATEID hidden field was posted</remarks>
  • protected override object LoadPageStateFromPersistenceMedium()
  • {
  • if (!String.IsNullOrEmpty(Request.Form["__VIEWSTATEID"]))
  • {
  • Guid viewstateID = Guid.Empty;
  • try
  • {
  • viewstateID = new Guid(Request.Form["__VIEWSTATEID"]);
  • }
  • catch
  • {
  • return null;
  • }
  • Object viewstate;
  • if (_viewstates.TryGetValue(viewstateID, out viewstate))
  • _viewstates.Remove(viewstateID); // Be carefull we remove the Viewstate so the user won't be able to make again the same request
  • return viewstate;
  • }
  • else
  • {
  • return null;
  • }
  • }
  • /// <summary>
  • /// Saves any view-state and control-state information for the page into a server Object.
  • /// </summary>
  • /// <param name="state">An <see cref="T:System.Object"></see> in which to store the view-state information.</param>
  • protected override void SavePageStateToPersistenceMedium(object state)
  • {
  • Guid viewstateID = Guid.NewGuid();
  • _viewstates.Add(viewstateID, state);
  • this.ClientScript.RegisterHiddenField("__VIEWSTATEID", viewstateID.ToString("N"));
  • }
  • }
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

/// <summary> 
/// This class save the viewstate value of each request on the WebServer. 
/// Don't use this on a server production ! If the application restart all the viewstates 
/// information will be loosed. You should save the viewstate in a DataBase or in any persistent storage. 
/// </summary> 
public class ServerViewStatePage : Page
{
    private static Object _lock = new object(); 
    private static Dictionary<Guid, Object> __viewstates;
    /// <summary> 
    /// Gets a dictionnary of viewstates stocked in the server. 
    /// </summary> 
    /// <value>The dictionary of viewstate stocked in the server.</value> 
    private static Dictionary<Guid, Object> _viewstates
    {
        get
        {
            lock (_lock)
            {
                if (__viewstates == null)
                    __viewstates = new Dictionary<Guid, Object>();
            }
            return __viewstates;
        }
    }

    /// <summary> 
    /// Loads any saved view-state information to the <see cref="T:System.Web.UI.Page"></see> object. 
    /// </summary> 
    /// <returns>The saved view state.</returns> 
    /// <remarks>Try to get the original viewstate if the __VIEWSTATEID hidden field was posted</remarks> 
    protected override object LoadPageStateFromPersistenceMedium()
    {
        if (!String.IsNullOrEmpty(Request.Form["__VIEWSTATEID"]))
        {
            Guid viewstateID = Guid.Empty;
            try
            {
                viewstateID = new Guid(Request.Form["__VIEWSTATEID"]);
            }
            catch
            {
                return null;
            }
            Object viewstate;
            if (_viewstates.TryGetValue(viewstateID, out viewstate))
                _viewstates.Remove(viewstateID); // Be carefull we remove the Viewstate so the user won't be able to make again the same request

            return viewstate;
        }
        else
        {
            return null;
        }
    }

    /// <summary> 
    /// Saves any view-state and control-state information for the page into a server Object. 
    /// </summary> 
    /// <param name="state">An <see cref="T:System.Object"></see> in which to store the view-state information.</param> 
    protected override void SavePageStateToPersistenceMedium(object state)
    {
        Guid viewstateID = Guid.NewGuid();
        _viewstates.Add(viewstateID, state);
        this.ClientScript.RegisterHiddenField("__VIEWSTATEID", viewstateID.ToString("N"));
    }

}

 Conclusion

Il suffit de mettre ce code dans le repertoire App_Code et de dériver votre page de Server ViewstatePage plutot que System.Web.UI.Page


 Historique

25 novembre 2006 16:39:28 :
Rajout d'un lock dans le cas où 2 threads tente en même temps d'accéder a _viewstates alors que __viewstates est null (merci Richard ;) ==> http://blogs.developpeur.org/cyril/archive/2006/11/25/enregistrer-la-viewstate-sur-le-serveur.aspx)
25 novembre 2006 17:38:30 :
Nouvelle remarque
26 décembre 2007 13:54:39 :
PageStatePersister : http://msdn2.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx

 Sources du même auteur

Source avec Zip Source .NET (Dotnet) UTILISATION DE LA MÉTHODE SORT ET SORTDIRECTION AVEC UN GRID...
Source .NET (Dotnet) RESPONSE.FILTER : MANIPULATION DU STREAM DE SORTIE ASP.NET
Source avec Zip Source .NET (Dotnet) OPTIMISATION DE LA SERIALISATION JSON POUR LES LIST<T>
Source avec Zip Source .NET (Dotnet) CRAWLABLELINKBUTTON : UPDATEPANEL ET RÉFÉRENCEMENT
Source .NET (Dotnet) POSTBACKCONTROL - COMMUNICATION CLIENT/SERVEUR AVEC LES UPDA...

 Sources de la même categorie

Source avec Zip Source .NET (Dotnet) GUESTBOOK AVEC GRIDVIEW par DanMor498
Source avec Zip CHECKED DROPDOWNLIST par fredzool
Source avec Zip Source avec une capture Source .NET (Dotnet) GRIDVIEW WITH TREEVIEW AND CALLBACK par fredzool
Source avec Zip APPELLER UN WEBSERVICE DEPUIS JAVASCRIPT par fredzool
Source avec Zip Source .NET (Dotnet) MONEY TEXTBOX WITH EMBEDED JAVASCRIPT par fredzool

 Sources en rapport avec celle ci

Source .NET (Dotnet) COMMENT CONSERVER L'ÉTAT D'UNE VARIABLE (SESSION ET VIEWSTAT... par jesusonline

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

afficher Image sur un datagrid suivant champ de données ? [ par coulis ] Voici mon probl&#232;me&nbsp;: (je travaille avec VS) Je veux afficher dans un &#171;&nbsp;datagrid&nbsp;&#187; une colonne avec des images. Mais ce afficher dans une colonne « datagrid » 2 champs de données ? [ par coulis ] Voici mon probl&#232;me&nbsp;: (je travaille avec VS) Je veux afficher dans une colonne &#171;&nbsp;datagrid&nbsp;&#187; 2 champs de donn&#233;es&nbsp Problème du au Viewstate ??? [ par stp_7 ] Salut,J'ai cr&#233;e un Custom web control (un time picker avec une dropdown list pour les heures et le minutes).Cet objet me sert &#224; l'encodage d problème dropdownlist [ par lenneth666 ] Voila alors j 'ai une datagrid. Dan sune colonne je veut que lorsque l'on passe en mode &#233;dition, un label laisse place a une dropdownlist.Et qd j Problème "Échec du chargement de viewstate" [ par jeremaub ] Voil&#224; mon souci: j'ai une page avec 2 textbox un bouton et un datagrid lorsque je clique sur le bouton j'execute une requete qui prend dans sa controls ajoutés dynamiquement [ par DeitY51 ] Bonjour, if (!IsPostBack){ // cree les datagrid dynamiquement CreerListeDemande(); // cree les panels contenant les datagrid CreerPanelsDemande() ViewState dans controles imbriqués [ par benjiiim94 ] Bonjour, J'utilise un controle datagrid dans un controle repeater. Lors d'une publication, les donn&#233;es de mon datagrid ne sont pas actualis&#233 DataGrid et ViewState [ par benjiiim94 ] Bonjour, J'ai un probl&#232;me pour cr&#233;er un datagrid qui utilise le viewstate, plus pr&#233;cisemment ce probl&#232;me l'&#233;v&#233;nement o utiliser viewstate [ par emna_bz ] Bonjour Je travail avec asp.net et c#.J'ai besoin d'utiliser viewstate .Je vais vous expliquer mon probleme:*j'ai un champ text et un boutton si on cl Désactiver la vérification du viewstate [ par Coolpix08 ] Voila pour rediriger mes variables vers une autre frame et sur une autre page aspx j'utilise un bouton submit HTML qui modifie, en javascript la frame


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,811 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales