-
-
Save mwjackson/3209966 to your computer and use it in GitHub Desktop.
mvc routes in your clientside codez
This file contains hidden or 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
// first register all your routes with names | |
MapRouteWithName(routes, | |
"Homepage", // Route name | |
"home", // URL with parameters | |
new {controller = "Home", action = "Index"} // Parameter defaults | |
); | |
private static void MapRouteWithName(RouteCollection routes, string name, string url, object defaults) | |
{ | |
var route = routes.MapRoute(name, url, defaults); | |
route.DataTokens = new RouteValueDictionary { { "RouteName", name } }; | |
} | |
// then grab all your routes and serialize them to json | |
public class RoutesGenerator | |
{ | |
public const string RouteName = "RouteName"; | |
public string AsJson(string webAppRoot) | |
{ | |
var clientSideRoutes = new Dictionary<string, string>(); | |
foreach (Route route in RouteTable.Routes) | |
{ | |
if (route.RouteHandler is MvcRouteHandler) | |
{ | |
string name = Convert.ToString(route.DataTokens[RouteName]); | |
if (string.IsNullOrEmpty(name)) continue; | |
clientSideRoutes.Add(name, string.Format("{0}{1}", webAppRoot, route.Url)); | |
} | |
} | |
var asJsonString = new JavaScriptSerializer().Serialize(clientSideRoutes); | |
return string.Format("{0}", asJsonString); | |
} | |
} |
This file contains hidden or 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
// and stick them wherever you like in your clientside | |
var routes = <%= new RoutesGenerator().AsJson(Url.Content("~")) %> | |
$.get(yourNamespacedRouteObject["RouteName"].format({ arg1 = someValue, arg2 = somethingElse)).... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment