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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13640559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:33:44  来源:igfitidea点击:

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

javascriptasp.net-mvc

提问by AliR?za Ad?yah?i

In external js file, I cant use

在外部js文件中,我不能使用

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.

怎么能 ?做这个?谢谢。

回答by archil

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

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

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

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

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

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

回答by Jorge Alvarado

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,

希望能帮助到你,

回答by Airn5475

Here's a pattern I've been using. It's a bit more steps, but I like that all of my urls are in one organized location in the View.

这是我一直在使用的模式。这是更多的步骤,但我喜欢我的所有网址都在视图中的一个有组织的位置。

At the bottom of my View I will include a Scripts Section that contains the urls like so:

在我的视图底部,我将包含一个脚本部分,其中包含如下所示的 url:

@section Scripts
{
    <script type="text/javascript">
        myJavaScriptObject.firstUrl = '@Url.Action("Action1", "Controller", new {id = Model.Id})';
        myJavaScriptObject.secondUrl = '@Url.Action("Action2", "Controller", new {id = Model.Id})';
    </script>
}

Inside of my JavaScript Class (which is in an external file) I will reference the url like so:

在我的 JavaScript 类(位于外部文件中)中,我将像这样引用 url:

var myJavaScriptObject = {
    firstUrl: '',
    secondUrl: '',
    docReady: function() {
        $.get(myJavaScriptObject.firstUrl, function(data) { do something...  });
    }
}

I realize the entries don't need to be referenced inside of the Class, but I like to have them there for my own housekeeping.

我意识到不需要在 Class 内部引用这些条目,但我喜欢将它们放在那里以供我自己整理。

回答by Muhammad Saqib

As accepted answer described, you can not use any C# code in external JS file. Here is what I normally do if I need to pass few controller links to my external .js file.

正如已接受的答案所述,您不能在外部 JS 文件中使用任何 C# 代码。如果我需要将几个控制器链接传递给我的外部 .js 文件,我通常会这样做。

In C# (.cshtml)

在 C# (.cshtml) 中

<script src="~/js/myfile.js"></script>

<script type="text/javascript">

    var url1 =  "@Url.Action("ActionName", "ControllerName", new { Param = ViewBag.Param })";  
    var url2 = "@Url.Action("AnotherAction", "AnotherController")";

    $(function() {
        window.initScript(url1, url2);
    });

</script>

In myfile.js

在 myfile.js 中

var _url1;
var _url2;

function initScript(url1, url2) {
    _url1 = url1;
    _url2 = url2;

   // other init. codes...

}

回答by Dinesh Gaud

You can use Hidden fields to do the same (on Master/Individual views).

您可以使用隐藏字段执行相同操作(在主视图/个人视图上)。

View page:

查看页面:

@Html.Hidden("commonUrlTrack", Url.Action("Action_Method_Name", "Controller_Name"))

<button onclick="commonFunction()">Click Me</button>

JS File:

JS文件:

function commonFunction() {
    var url = $("#commonUrlTrack").val();        
    alert(url);        
}