Thursday, November 18, 2010

Creating a ASP.NET MVC HTML Helper for Silverlight

Over the last few weeks I have started investing some time in learning ASP.NET MVC (specifically ASP.NET MVC 2).  This has nothing with the ongoing "Silverlight is dead" debate and I actually started a deep dive into the technology back in August 2010.  I think that ASP.NET MVC is very important for Silverlight developers to learn (more on this in another blog post), because of its obvious positioning in Microsoft's HTML5 tooling investments (more on that in MIX 2011).
Intro to HTML Helpers
HTML Helpers have the following qualities:
Usually implemented via extension methods
Usually implemented part of a static class
In .NET 4.0/C# 4.0 utilize optional parameters to minimize the initialization signature
Used inline with HTML in ASP.NET MVC Views to create dynamic content, while minimizing the code written and maintained
Basically an HTML helper is a extension method that takes some parameters and renders HTML.  In ASP.NET MVC you have complete control over the rendering of the HTML in your Views.  If you are an ASP.NET developer you can think of it as having the ability to dictate the exact HTML/Javascript that gets surfaced when you drag over any ASP.NET server control.  For example, if you drag over an ASP.NET button server control, ASP.NET handles how that control is rendered on the page.  Of course in ASP.NET you could override the rendering from the server, however it was a major pain.
HTML Helpers in ASP.NET MVC are there to minimize how much code you need to write.  For example, instead of having to write 100 lines of HTML every time there is an input form.  You could create an HTML Helper that does this for you.  This minimizes the code, improves maintenance of your code and abstracts that component into its own SRP (single responsibility principle) method.
ASP.NET MVC versions 1 through 3 include a ton of HTML Helpers.  These helpers include basic methods for rendering simple HTML like a text box to more complex helpers.  If you download the ASP.NET MVC 3 source code, you will see a lot of very complex HTML Helpers.  These HTML helpers can render complex HTML with interactive HTML.  For example, my companion site (http://www.silverlightbusinessintelligence.com) for my Silverlight business intelligence book utilizes the Twitter HTML helper that renders my tweets in a nice interactive HTML component with JavaScript that makes the appropriate web service requests.  Some of the advanced HTML helpers include: Facebook, Twitter, video etc.  The beauty of this is that in order to utilize this component I just had to reference it using one line of code.


Read more: Silverlight Hack