Sunday 13 April 2014

ASP.NET MVC - 3rd party integration with HtmlHelper

We had an interesting requirement recently where we wanted to create new extension methods for HtmlHelper class in an web (ASP.NET MVC) solution. One interesting requirement was to write extension method such that we could integrate a 3rd party JavaScript control. Usually integration with any 3rd party control requires following steps:

  1. Adding requisite content e.g. JavaScript files, CSS (or LESS) files to solution. (manual step, can be automated if NuGet package is available) 
  2. Include the added content to views (or the layout page).
  3. Add required HTML to the page and add the necessary JavaScript code to let the 3rd party control take effect.

It was the 3rd step that we wanted to encapsulate in an extension method to ensure that developers do not need to write boiler plate code (and avoid mistakes in the boiler plate code). Adding generated HTML was quite straightforward but adding JavaScript took some decision making time mainly due to the fact that as a general practice you want to add JavaScript code after
tag and it is not available in HtmlHelper context. So we took a conscious decision:
  1. Use ViewContext.ViewBag in HtmlHelper extension method to add Scripts to a List.
  2. Use Layout page to render all the scripts added to the ViewBag. We needed to use ViewContext.ViewData["name of dynamic property"].
It was basically similar to what ScriptManager of ASP.NET WebForms does :)