Dynamic loading of Usercontrols and resources (CSS, JS) RRS feed

  • Question

  • User918375229 posted

    Hey everyone,

    we got a problem with our customer management system that is currently in development.

    We got a HTML template that we use, that has serval CSS and JS files for the design and the functionality. We want to have a dashboard for our customers where they can add and view serval controls, like statistics and stuff. We splitted eveything into UserControls (Form to add a user, form to edit a user) couse we want to be able that the customer can create his individual dashboard.

    So the main problem is, that every form control needs the CSS and JS for the form stuff. Every diagramm control needs the CSS and JS for the diagramm stuff. Actually we dont know how to realise this. So how can we archive that we can load usercontrols dynamicly, and how can we archive that the right styles are loaded in the <head>.

    Is there any way to access a contentplaceholder from a usercontrol and add the needed stuff to it ? I just want to load the CSS and JS when it is needed.

    Friday, July 25, 2014 4:41 AM

All replies

  • User-1611549905 posted

    The easiest way to do this is with an asset manager -- my preferred option here is Cassette (http://getcassette.net/). You can define bundles of CSS and JS files and just pull in the ones you need using Bundles.Reference() in your user controls. It works equally well with Web Forms or ASP.NET MVC. In addition to just giving you the assets you need, it also allows you to bundle and minify your CSS and JS, and to use pre-processors as well such as LESS, SASS/SCSS, CoffeeScript or TypeScript.

    Friday, July 25, 2014 10:47 AM
  • User918375229 posted

    Okay that sounds pretty nice :)

    But how can i archive that the control adds the styles and stuff to the <head> BEFORE the complete page was loaded ?

    Couse when the page with the controls load, the control itself should report what styles and css is used, and add it to the <head> not in the middle of the webpage.

    Friday, July 25, 2014 11:21 AM
  • User-1611549905 posted

    Cassette will do that.

    You add Bundles.Reference() in the Page_Load event in your codebehind, and then put Bundles.RenderStylesheets() and Bundles.RenderScripts() where you want them to be rendered.

    You can also do the same thing in your MVC views -- Cassette does a bit of clever jiggery-pokery to make that work properly as well.

    Friday, July 25, 2014 12:21 PM