Question

I have tended to shy away from adding properties to my ASP.NET pages. It never seemed like a great idea to me. However, recently I have seen the practice employed in a few sample applications. Has my aversion to adding custom properties to a page been unwarranted or is this a "it depends" situation?

Was it helpful?

Solution

The thing about properties you need to remember is that they last for the entire page lifecycle. This makes them both very useful (set a property early in the lifecycle and it's still valid later) and dangerous (it's easy to access a property before it's set, or not realize another life-cycle phase changed it on you).

One area I've seen properties used to great effect is as a good type-safe way to wrap the query string and Session. Define properties for each of your expected query string or session values and it becomes very clear to future developers what is expected and available.

Another common use is to wrap ViewState items. I expect this is where you're seeing them in samples, since most samples tend to assume ViewState is turned on.

OTHER TIPS

I see nothing wrong with using properties to cleanup the code on a server side page. I like to use properties to access Session State or View State information, this way if I modify how I access the data, I only change one place.

Asp.net doesn't supports constructor based injection. This is a clear scenario where you want to use asp.net properties (as you can use property based injection).

Update 1: Here is a similar scenario but for controls - How to use Dependency Injection with ASP.NET Web Forms

Update 2: It is ok to use them to wrap viewstate or query string. I would look at it carefully though, as you don't want to abuse the codebehind. If you see you are using one of the wrapping properties on the codebehind plenty of times, there is probably too much code in the codebehind. Looking at it this way, has the side effect of avoiding repeated casting/parsing that can be associated to those properties.

There is nothing wrong with properties on a page. They might see odd since a page is rarely manipulated as an object by external code but it can be done. Given that, most properties on a page can be marked private. Like all things, there are exceptions.

One of the biggest uses I have for properties on my page is when wrapping a ViewState value:

protected string TaskName
{
    get { return (string)ViewState["TaskName"] ?? string.Empty; }
    set { ViewState["TaskName"] = value; }
}

In this case, I have marked the property as "protected" which allows me to access it from my markup.

Why would it be bad? Properties are really just methods and I am sure you add methods to the page all the time.

I use properties on my asp.net pages to access Session, Viewstate and querystring. It just makes you write less code and increases readability

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top