Tuesday, March 10, 2009

It's Official I'm addicted to MVC Html Helpers

If you've been using MVC recently and haven't been using your own HTML helpers then I suggest you do!

I started off using HTML helpers very sparingly probably because I didn't understand them enough, however onced I'd started just "doing it" the more and more HTML Helpers I seem to create, they are easy to develop and makes your HTML view pages so much nicer and cleaner.

On my latest project I've gone absolutely nuts I have so many helpers its not funny (you can never have enough can you?). I've cut some of my HTML pages from a few hundred lines down to about 50 and because my website is so "modula" in design it makes it easy to plug in modules to different pages.

For example we have crap loads of google adsense on the site, we need to have different adsense for different pages so they fit within the allocated space etc. So at the moment we are storing all the adsense code in the database and then just using helpers to pull out the one we need.

And our MVC helper is:

public static string GoogleAdsense(this HtmlHelper helper, int AdsenseID)
SoccerDataContext s = new SoccerDataContext();
return s.tbl_settings_adsenses.Single(t => t.tbl_settings_adsense_id == AdsenseID).Description;

Probably my favourite helper at the moment is the "header" helper, basically every item on out website sites in a box with a colour header see below of example page with 4 headers.

My helpers then look like this, which I can change the colour with ease, saves have to copy and paste html code form one page to another.

<%=Html.StartHeader("Sponsored Links", "green", "") %>
<%=Html.GoogleAdsense(0) %>
<%=Html.EndHeader() %>

What are some of your favourite html helpers you have produced?

No comments: