Last week I got a request from a customer whom was developing a custom ASP.NET control targeted for other developers, and one of his requirements was to persist the control's properties in the html markup, even for the default values which normally Visual Studio removes: since those are default values the assumption is that we don't need to persist them in the markup (what usually happens is that if you change the value of a property through the property grid this is reflected in the html markup, but if you later set the value back to its default the designer removes the corresponding markup since it's no longer needed), but the requirement here was to persist them anyway.
To be honest I had never thought to this possibility (who knows, maybe I'm too used to do things in the Microsoft way ) and despite my researches I've not been able to find this answer anywhere in our internal docs and samples, so we started working on a sample together (well, me from my office in Milan and the customer in his office in Crecchio, central Italy) and we also involved an Escalation Engineer (Radomir Zaric, thanks for your help!) to clarify a few weird behaviors and internals we encountered during our tests.
To make a long story short, basically we came up with a solution based on two fundamentals:
- Use the ToolboxData attribute which creates the markup when the control is first dragged from the toolbox on the page
- Use the DesignerSerializationVisibility attribute (set to Content) which generates initialization code for each public not hidden property of our control
If you can read Italian, Andrea (the customer) posted the solution to his blog: Valori di default per un ASP.Net WebControl; he promised to publish an English translation soon, add a comment to the post if you're eager to read it
By the way, here is another interesting posts in February (I did not have time to read the past month yet): La persistenza delle proprietà di un WebControl senza utilizzare il Postback (How to persist a control property without using the postback).
UPDATE (18/02/2008): here's Andrea's first translation: How to persist a control property without using PostBack
CarloQuote of the Day:
Civilization begins with order, grows with liberty, and dies with chaos. --Will Durant