ASP.NET: Automatic field persistence · Curiosity is bliss

Curiosity is bliss    Archive    Feed    About    Search

Julien Couvreur's programming blog and more

ASP.NET: Automatic field persistence


Found on Juye's Blog, a custom attribute that is used to automatically persist fields from the codebehind class to the ViewState or the Session.
It is unclear to me that it makes the code really much shorter or clearer, or that it is efficient in any way, but it still is a cool trick. ;-)

In the .aspx:

<%@ Register TagPrefix="juye" Namespace="Juye.Web.State" Assembly="Juye.Web.State" %>
<juye:persister id="persister" runat="server"/>

In the .cs:

public string Name;

In place of (the boring):

public string Name
get{ return (string)ViewState["Name"]; }
set { ViewState["Name"] = value; }

A custom control, the Persister, needs to be added in the page (see aspx sample above). It gets called via the Control.LoadViewState and Control.OnInit hooks, which gives it a chance to inspect all fields from the page (using the Page.GetType().GetFields() reflection call) to find those marked with the custom Persist attribute.
It supports persisting to the ViewState with [Persist(PersistMode.ViewState)] and to the Session with [Persist(PersistMode.Session)].

Here is the zip containing the code, with a sample.


The CodeProject has an article on automatic persistence in ASP.NET forms, that persists to the DB (not just the Session or ViewState):

Posted by: Dumky (June 18, 2003 11:27 AM)
comments powered by Disqus