Assets in MVC4
Edit: The Assets feature was removed from the RTM in favor of bundling and minification.
In MVC4 they’ve added an API to centralize script and style sheet includes when rendering a complex view with partials and a layout template.
The problem is a single view might have many partials that all need the same script or style sheet. How do they “know” that the script or style sheet they depend upon is included and only once? Previously, that was up to the developer coordinating the views, partials and layout template in MVC to come up with a solution.
Now with MVC4 the Assets API provides a way for a view or a partial to indicate they require a script and for a layout template to indicate where those scripts and style sheets should be rendered:
public static class Assets
{
public static void AddScript(string scriptPath);
public static void AddScriptBlock(string block);
public static void AddScriptBlock(string block, bool addScriptTags);
public static void AddStyle(string cssPath);
public static void AddStyleBlock(string block);
public static void AddStyleBlock(string block, bool addStyleTags);
public static IHtmlString GetScripts();
public static IHtmlString GetStyles();
}
Now a partial can indicate a script or style sheet to include:
@{
Assets.AddScript("~/Scripts/jquery-1.7.1.js");
Assets.AddStyle("~/Content/Foo.css");
}
<h2>Some Partial</h2>
And the layout template can render those assets:
<!DOCTYPE html>
<html>
<head>
@Assets.GetStyles()
</head>
<body>
@RenderBody()
@Assets.GetScripts()
</body>
</html>
Trackbacks