Created
August 29, 2012 11:00
-
-
Save drphrozen/3510621 to your computer and use it in GitHub Desktop.
Using Javascript and ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body data-controller-and-action="@ViewContext.GetControllerAndActionAsJson()"> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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