Introduction
A nice feature of ASP.NET MVC is how Controllers and Views become automatically related through method names, file names, and directory structure. Some Views can have some related JavaScript code that could be separated in files (js) and I was wondering if there were some patterns to organize these JavaScript and make them automatically included in each correspondent View.
After some research, I found this article by Shayne P Boyer but my project uses ASP.NET MVC 3 with the Razor View Engine.
Besides, I was concerned about Partial Views that could have their own related JavaScript file, and was thinking in a way to make these scripts included once on the page even if the same Partial View is used multiple times on the same Page.
Here I show a ViewPageBase
that automatically references JavaScript files for the current View and for the inner Partial Views (using the structure suggested by Shayne and avoiding that the same file is registered more than once).
ViewPageBase
ViewPageBase
inherits System.Web.Mvc.WebViewPage<TModel>
and overrides the InitializePage
method that will search for the related JavaScript file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using System.Text;
using System.IO;
namespace JSOrganization
{
public abstract class ViewPageBase<T> : WebViewPage<T>
{
protected override void InitializePage()
{
base.InitializePage();
AddScriptForView(this.VirtualPath);
}
The AddScriptForView
method will check if the JavaScript file exists for the View and, if so, will keep the reference.
void AddScriptForView(string path)
{
if (string.IsNullOrEmpty(path)) { return; }
var dctScripts = GetScriptsDictionary();
if (!dctScripts.ContainsKey(path))
{
path = path.Replace("~/Views/", "~/ViewScripts/");
path = Path.ChangeExtension(path, "js");
if (File.Exists(Server.MapPath(path)))
{
var tagBuilder = new TagBuilder("script");
tagBuilder.Attributes.Add("type", "text/javascript");
tagBuilder.Attributes.Add("src", Url.Content(path));
dctScripts[path] = string.Format("{0}{1}",
tagBuilder.ToString(TagRenderMode.Normal), System.Environment.NewLine);
}
}
}
GetScriptsDictionary
will search, in the current HttpContext
, the dictionary that keeps the JavaScript file references. At this point, the program identifies the first View processed, which is usually the View returned by the current Action and will include later all the script references in the final HTML.
bool isPrincipalView = false;
const string _viewScriptsKey = "__ViewScripts";
private Dictionary<string, string> GetScriptsDictionary()
{
var ctx = Context;
var dctScripts = default(Dictionary<string, string>);
if (!ctx.Items.Contains(_viewScriptsKey))
{
isPrincipalView = true;
dctScripts = new Dictionary<string, string>();
ctx.Items[_viewScriptsKey] = dctScripts;
}
else
{
dctScripts = ctx.Items[_viewScriptsKey] as Dictionary<string, string>;
}
return dctScripts;
}
Then, ExecutePageHierarchy
is overridden. It's where the "Principal View" inserts all the JavaScript references at the top of the HTML.
public override void ExecutePageHierarchy()
{
base.ExecutePageHierarchy();
if (isPrincipalView)
{
var dctScripts = GetScriptsDictionary();
var sw = this.Output as StringWriter;
var sb = sw.GetStringBuilder();
AddScriptForView(this.Layout);
AddScriptForView("~/Views/_ViewStart.cshtml");
foreach (var pair in dctScripts)
{
sb.Insert(0, pair.Value);
}
}
}
}
public abstract class ViewPageBase : ViewPageBase<dynamic> { }
Using the base view class
To make it work, it's necessary that all the Views inherits from ViewPageBase
. There are two ways to accomplish this.
One way is inheriting per-View, inserting the following clause at the top of each View:
@inherits JSOrganization.ViewPageBase
Another way is to specify in Views/Web.config the base class for all the Views:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="JSOrganization.ViewPageBase">
Project organization
The project structure must be like the following example:
In the example above, each View has your associated JavaScript file in the ViewScripts folder. Remember that even a partial View can have its own JavaScript that will be referenced just once, even if the View is rendered multiple times in a parent View.