外部js文件中的Asp.Net Mvc Url.Action?

Ali*_*hşi 59 javascript asp.net-mvc

在外部js文件中,我无法使用

url = "@Url.Action("Action", "Controller")" 
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.
Run Code Online (Sandbox Code Playgroud)

我写这样的时候:

url = "/Controller/Action"
Run Code Online (Sandbox Code Playgroud)

如果项目位于子文件夹下,则脚本不起作用.我需要这样的东西作为相对的Url:

url = "~/Controller/Action"
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?谢谢.

arc*_*hil 146

由于.js文件未被asp.net mvc视图引擎解析,因此您根本无法在其中使用任何c#代码.我建议使用不引人注目的方法,就像这样

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

在javascript中,使用值 data-request-url

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


Jor*_*ado 8

我不确定这是否是最优雅的解决方案,但我所做的是区分寄存器和外部脚本中的实际实现,以便:

<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...);
}
Run Code Online (Sandbox Code Playgroud)

所以在我的视图中我只有寄存器函数和脚本包含特殊值作为参数来做我想做的事情.

希望能帮助到你,