Skip to content

Instantly share code, notes, and snippets.

@drphrozen
Created August 29, 2012 11:00
Show Gist options
  • Save drphrozen/3510621 to your computer and use it in GitHub Desktop.
Save drphrozen/3510621 to your computer and use it in GitHub Desktop.
Using Javascript and ASP.NET MVC
<body data-controller-and-action="@ViewContext.GetControllerAndActionAsJson()">
// using jQuery
// NS is just some global namespace, replace as you see fit
NS = {
init: function() {
var mvcContext = $('body').data('controller-and-action');
NS.Context.controller = mvcContext.controller.toLowerCase();
NS.Context.action = mvcContext.action.toLowerCase();
var callIfFunction = function(arg) { if ($.isFunction(arg)) { arg(); } };
// execute __global__ first, then the controller specific function and at last the action specific function
callIfFunction(NS.Handlers.__global__);
var controller = NS.Handlers[NS.Context.controller];
if(!controller) return;
callIfFunction(controller.init);
var action = controller[NS.Context.action];
if(!action) return;
callIfFunction(action.init);
}
};
NS.Context = {
controller: null,
action: null
};
// now define which function are to be executed for each scope
NS.Handlers = {
__global__: function () {
// global init functions
},
home: {
init: function() {
},
index: {
init: function() {
}
}
},
account: {
// and so on
}
}
// load everything when dom has loaded
$(NS.init);
public static class ViewContextExtensions
{
public static string GetControllerAndActionAsJson(this ViewContext viewContext)
{
var controller = viewContext.Controller;
if(controller == null) return "{}";
var valueProvider = controller.ValueProvider;
if(valueProvider == null) return "{}";
var actionName = valueProvider.GetValue("action");
var controllerName = valueProvider.GetValue("controller");
return Json.Encode(new
{
controller = controllerName == null ? null : controllerName.RawValue as string,
action = actionName == null ? null : actionName.RawValue as string
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment