I need to supply a URL as an argument in javascript. This is needed because I have a method on a shared page that gets used by several other pages, but the method needs to call different URLs depending on the source page.
If I try it this way, the URL gets called on page-load, which is NOT wanted:
myMethod('@Url.Action("myMethod", "myController")');
function myMethod(myURL) {
window.open(myURL + arguments);
}
If I try it this way, the words “method” and “controller” get underlined, and the page doesn’t load:
myMethod("myMethod", "myController");
function myMethod(method, controller) {
window.open("@Url.Action(method, controller)" + arguments);
}
You seem to be mixing javascript and server side code here. One possibility would be to have either a global javascript variable in the view that will point to the url or use HTML5 data-* attributes on some DOM element. For example inside the view you could define an invisible span tag which will hold the url:
and then in your separate javascript file when calling the method:
You would of course modify your global javascript function to take directly an url and not action and controller: