Tag Archives: NuGet

Content Injector for ASP.NET MVC

If you ever created reusable components for ASP.NET MVC, you’ve probably faced with the issue, that a partial view or a HTML helper requires one or more external CSS stylesheets or JavaScript files. If you consider code performance and quality, you always insert your CSS files at the top, and your JS files at the bottom of the page, paying attention to load them exactly once, even if multiple parts of your page require them. However, that’s not easy, because partial views and HTML helpers are rendered autonomously. Although the problem is not new at all, it’s not easy to solve in WebForms, and definitely difficult in MVC.

You may be not surprised that the freshly baked solution is delivered by Peter Blum in the form of the Content Injector for ASP.NET MVC toolkit. Experienced ASP.NET developers probably saw this name several times, because Peter creates reusable ASP.NET WebControls in his one-person company. Among them probably the most well-known is the Peter’s Data Entry Suite (DES), which contains more than 100 webcontrol that simplify input handling and validation. The DES is a very useful set of components, so it’s not a coincidence that it received many positive feedback, excellent rating and professional awards.

So it was not surprising, that a few weeks ago it was Peter, who came up with an idea in the ASPInsiders list, that solves the problem above. Many of us tried and tested the tool, and provided feedback that he quickly applied to the source code, so I can now full heart recommend the Content Injector for ASP.NET MVC toolkit, especially in the NuGet package form.

Using the package is very straightforward. First, you have to mark the places on your Layout.cshtml page, where you want to insert custom content:

@Injector.InjectionPoint("ScriptFiles")

Next, if for example a view requires the jQuery Validate library, then you can insert the corresponding script files directly from the view:

@Injector.ScriptFile("~/Scripts/jquery.validate.min.js"); 
@Injector.ScriptFile("~/Scripts/jquery.validate.unobtrusive.min.js");

Of course this is only the simplest use case, you can specify additional parameters (eg. order), or you can insert stylesheets, scripts, meta tags, hidden fields, script blocks or anything else, thanks to the extensible and configurable (eg. tracing) nature of the product. You can read about all those options in details in the 23-page User’s Guide.

Another interesting thing is that reacting to the first feedback, Peter connected the Content Injector with the Microsoft Web Optimization Framework, so after installing the ContentInjector.WOF NuGet package, you can insert StyleBundle and ScriptBundle as well.

Downloads:

Grab it, try it, and don’t forget to send him feedback or just a quick thank you!

 

Technorati-címkék: ,,