title: How to encapsulate a reusable "control" for ASP.NET MVC 3 + Razor views
body: <p>I am looking for best practices on how to create a reusable "control" for use on several MVC 3 views.  I could make an Html helper extension method (programmatically or with the declarative helpers in razor) or I could create a partial view.  </p>
  
  <p>The trick, in my case is that I need to do more than just dump some HTML in precisely the spot that the view calls the helper/partial.  In addition to putting some HTML markup in that spot, I also need to add some javascript code to make it work.  Normally, I would put this code elsewhere in the page (e.g. the bottom).  This is of course strictly not required.  Also, note, the javascript is not control instance specific.  In other words, it is possible to write javascript that finds all instances of the control HTMl markup on a page and "activates" it with appropriate events, etc.</p>
  
  <p>I have thought of several possibilities.</p>
  
  <ol>
  <li>Have the helper/partial dump out the HTML and a <code>&lt;script&gt;</code> tag right in the place it is called.  This seems like a bad idea since it means the control could only be used once per page.</li>
  <li>Have two helpers.  One to output the HTML markup, and a second that spits out the javascript.  The second would be called only ever once and would be called from the bottom of the page so that the script ends up in the right place.  If I invented a second control that was like this, I would have 4 helpers (2 for HTML, 2 for Javascript).</li>
  <li>Invent some kind of ScriptManager that controls can register javascript with.  The scriptmanager would have some kind of helper that would be added to the bottom of pages and would dump out the javascript for all controls that had registered some snippet of script.  The call to the scriptmanager helper could be in the _layout.cshtml so that it automatically happens on any page that needs it.  It would do nothing when a page didn't need it.  This doesn't seem very MVC-ish, I guess.</li>
  <li>Just have a helper that spits out the HTML and then add the javascript to the site.js that is included on every page.  The javascript would be smart enough to not do anything if it could not find any relevant markup on the page (markup would have a wrapper element with a particular class).  There would be overhead of this search for markup on all pages though, including pages that don't have any of these controls.</li>
  <li>Same as #4, but put the javascript in its own .js file and include it only on pages that use the control.  This is more efficient for pages that don't use the control, but it is an additional .js file and associated HTTP request for pages that do.</li>
  </ol>
  
  <p>I am leaning towards #4, but is this a solved problem?  Is there a better, 6th option?</p>