When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.
It is then very easy to do this:
var xhr = $.ajax({
url: '<%= Url.Action("DisplayItem","Home") %>/' + el1.siblings("input:hidden").val(),
data: { ajax: "Y" },
cache: false,
success: function(response) { displayMore(response, el1, xhr) }
});
…then including the URL in the ajax call using Url.Action() inside the JS is pretty easy. How could i move this do its own JS file when without hard coding the URL?
This way fully uses MVC Routing so you can fully take advantage of the MVC framework.
Inspired by stusmith’s answer.
Here I have an action in
ApplicationControllerfor dynamic javascript for this URL :I’m including static files here because I want just one master javascript file to download. You can choose to just return the dynamic stuff if you want:
This is the helper function that creates our lookup table. Just add in a line for each RouteUrl you want to use.
This generates the following dynamic javascript, which is basically just a lookup table from an arbitrary key to the URL I need for my action method :
In cart.js I can have a function like this.
Note that the url parameter is taken from the lookup table :
};
I can call it from anywhere with just :
This seemed to be the only way I could come up with that would allow me to use routing in a clean way. Dynamically creating URLS in javascript is icky and hard to test. Testing types can add in a layer somewhere in here to easily facilitate testing.