Asp.Net Mvc Url.Action in external js file?

In external js file, I cant use

url = "@Url.Action("Action", "Controller")" 
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.

When I write like this:

url = "/Controller/Action"

And If project is under a sub folder, then scripts do not work. I need something like this as relative Url:

url = "~/Controller/Action"

How can ı do this? Thanks.


Solution 1:

As .js files are not parsed by asp.net mvc view engine, you simply cannot use any c# code in there. I would suggest using unobtrusive approach, something like this

<div id="loader" data-request-url="@Url.Action("Action", "Controller")"></div>

And in javascript, use value of data-request-url

$(function(){
   $('#loader').click(function(){
       var url = $(this).data('request-url');
       alert(url);
   });
});

Solution 2:

I'm not sure if this is the most elegant solution, but what I did was differentiating between registers and the real implementation in the external scripts, so that:

<script>...</script>
... include all the external scripts I need

$(document).ready(function(){

    //get all the information you need from your MVC context 
    //before going out of context and into the scripts
    var url = '@Url.Action("Action", "Controller")'; 


     RegisterMyFunction(url, other parameters ..);
     RegisterAnotherFunction(url, others...);
}

So that in my views I only had the register functions and the scripts contained the special values as a parameter to do whatever I wanted.

Hope it helps,