What’s the best way to avoid hardcoding URL’s in JavaScript (primarily used when making AJAX calls)?
In the past:
- Render JavaScript variable with result of
@Url.Actionor@Url.RouteUrl - Pass result of
@Url.Actionor@Url.RouteUrlto JavaScript in init/ctor.
Is there a better way?
It would be good to do something like this:
var url = $.routes("actionName", "controllerName") // or "routeName" for named routes
$.post(url, { id = 1 }, function() { //.. });
Which of course isn’t really possible (JavaScript doesn’t have direct access the to the ViewContext and thus doesn’t have access to the route tables).
But i’m wondering if there’s a way i can kind of setup my own “route table” for JavaScript, with only the ones i know it would need? (e.g i set it up in the View)
How do people handle this?
Implementing a Javascript routing engine wouldn’t be too difficult. First, serialize the Routes from C# to Javascript. Second, recreate the
Url.Actionmethod.However, that’s a bit overkill for any of the projects I’ve worked on. My team’s projects have always rendered a common Javascript variable that holds all necessary URL’s.
This approach ensures strongly-typed action methods and lends better to refactoring too.