Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Last active December 10, 2015 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/4438411 to your computer and use it in GitHub Desktop.
Save kamranayub/4438411 to your computer and use it in GitHub Desktop.
RenderRoutes renders a JSON object that contains all your named routes, as long as you're using AttributeRouting
<!-- In your CSHTML file -->
<script type="text/javascript">
window.routes = @RouteTable.Routes.RenderRoutes();
</script>
// RenderRoutes extension
//
// Use with AttributeRouting and JSON.NET to
// render out a JSON object that contains all your
// named routes for use in your client scripts.
public static class RouteExtensions {
/// <summary>
/// Renders a JSON object of routes
/// </summary>
/// <returns></returns>
public static IHtmlString RenderRoutes(this RouteCollection routes) {
var json = new Dictionary<string, string>();
foreach (IAttributeRoute route in routes.OfType<IAttributeRoute>()) {
if (!string.IsNullOrWhiteSpace(route.RouteName) && !json.ContainsKey(route.RouteName)) {
json.Add(route.RouteName, "/" + route.Url);
}
}
// Web API
// .OfType<>() doesn't seem to work?
foreach (var route in GlobalConfiguration.Configuration.Routes)
{
if (route is IAttributeRoute)
{
var r = route as IAttributeRoute;
if (!string.IsNullOrWhiteSpace(r.RouteName) && !json.ContainsKey(r.RouteName))
{
json.Add(r.RouteName, "/" + r.Url);
}
}
}
return MvcHtmlString.Create(JsonConvert.SerializeObject(json));
}
}
// Namespace
window.app = window.app || {};
// Router utility
app.Router = (function (routes, _, undefined) {
var router = {};
//
// Public
//
router.url = function (routeName, parameters) {
var finalUrl = routes[routeName];
if (!_.isString(finalUrl)) {
return undefined;
}
// Parse URL
if (parameters) {
if (_.isObject(parameters)) {
// Parameter map
for (var param in parameters) {
finalUrl = finalUrl.replace('{' + param + '}', parameters[param]);
}
} else if (parameters !== undefined) {
// Only one parameter, replace it with given value
var rx = new RegExp('\\{[A-z0-9_]+\\}', 'gi');
finalUrl = finalUrl.replace(rx, parameters);
}
}
return finalUrl;
};
return router;
})(window.routes, _);
// Somewhere else in your app...
// Given:
//
// window.routes = {
// product: "/products/{productId}",
// productPhoto: "/products/{productId}/photo/{photoId}"
// }
app.Router.url("product", 5);
// returns /products/5
app.Router.url("productPhoto", { productId: 5, photoId: 6 });
// returns /products/5/photo/6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment