Sunday, January 13, 2008

Enum To Collection: Make Binding Easy

I prefer storing domain data for applications in an Enum, when that data seldom/rarely changes. In doing so, I find that I need to display this data in the form of a DropDownList in the UI. Through a generic "Enum To Collection" method, and the use of ObjectDataSources, this task is very easy.

Here is the generic static method to turn an Enum into a Collection:


public static Collection<KeyValuePair<string, int>> ToCollection<T>()



{



Collection<KeyValuePair<string, int>> collection = new Collection<KeyValuePair<string, int>>();







Array values = Enum.GetValues(typeof (T));







foreach (int value in values)



{



collection.Add(new KeyValuePair<string, int>(Enum.GetName(typeof (T), value), value));



}







return collection;



}

I then define a static method in my business class decorated with the DataObject attribute:


[DataObjectMethod(DataObjectMethodType.Select)]



public static Collection<KeyValuePair<string, int>> GetDays()



{



return EnumHelper.ToCollection<Days>();



}
Then, just drop a DropDownList control onto your page. Use the Configure Data Source wizard to select your static method you just defined:



And that's it. Check it out:




Note: I like to set "AppendDataBoundItems" to true, and add my "-Select-" value on the page. This is nice because I don't have to deal with that logic in my business tier.

Hope you like it and happy binding.

Friday, January 4, 2008

Easy trick to decreasing your page size!

While working on a project with Than Nap, a fellow Slalom consultant, I picked up a simple trick to decreasing your page size.

If you have worked with MasterPages in ASP.NET 2.0, you have no doubt been looking at the source of a page, and seen something like the following....





The naming convention of controls following the hierarchy of pages in which the control is nested. When the ID of a masterpage is not explicitly set, it defaults to ctl00. When you add a new MasterPage to a project/website, you get default content like the following...



If you just start going from here, you may be making a mistake. The names you give (or don't give) your MasterPage and ContentPlaceHolders show up twice per control. And you might be appalled if you look at the source for a gridview/detailsview.

Here's the tip:

  1. Name your contentplaceholders with as short of name as possible. I use "c" for a main content area, "t" for a title, and so on.

  2. Add the following piece of code to code behind of your MasterPage.



The same example I started with (btnSave) would now look like this in source...




In larger applications, with complex web forms, this little trick may get you a 10% decrease in page size alone!