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:
...
<juye:persister id="persister" runat="server"/>
...
In the .cs:
public string Name;
In place of (the boring):
{
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):
http://www.codeproject.com/useritems/TransparentForms.asp