Use JavaScriptModel in a global filter

If you have global variables which should be set on every page or javascript functions which should be executed on every page you should consider to use filters.

The following example shows how to create a filter which handles global variables and function calls.

/// <summary>
/// Called before the action result executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
	// filtering on child actions is not necessary
	// and ignore filter for ajax calls
	if (filterContext.IsChildAction || 
	filterContext.HttpContext.Request.ContentType.Contains("application/json"))
		return;

	IJavaScriptModelAware javaScriptModelAware
		= filterContext.Controller as IJavaScriptModelAware;

	if (javaScriptModelAware == null)
		return;

	#region Global JavaScript variables

	javaScriptModelAware.AddJavaScriptVariables(PageLoadEvent.Init,
		"Config.Language", Thread.CurrentThread.CurrentUICulture.ToString(),
		"Config.SomeConfigValue", 1234
		);

	javaScriptModelAware.AddJavaScriptVariables(PageLoadEvent.Ready,
		"GoogleAnalyticsController.ID", "You could get this from your config"
		);
	#endregion

	#region Global JavaScript functions

	// In our example Config.Init has to be called before all action functions.
	// --> so we insert the function to the queue.
	javaScriptModelAware.InsertJavaScriptFunction("Config.Init", PageLoadEvent.Init);
	javaScriptModelAware.AddJavaScriptFunction("GoogleAnalyticsController.Ready");

	#endregion
}

Last edited Feb 1, 2013 at 12:14 PM by acuntex, version 5

Comments

No comments yet.