Skip to content

Assets in MVC4

March 26, 2012

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>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: