javascript javascript中的MVC“〜”路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16250190/
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-10-27 03:54:06  来源:igfitidea点击:

MVC "~" path in javascript

javascriptasp.netpathrelative-path

提问by sam

I use JavaScript code to call an MVC web API. It works fine when the current path is:

我使用 JavaScript 代码来调用 MVC Web API。当前路径为:

http://localhost/myApp/Administrator

http://localhost/myApp/Administrator

but it fails when current path is:

但是当当前路径为:

http://localhost/myApp/Administrator/

http://localhost/myApp/Administrator/

I get the error The resource cannot be found. Below is the code:

我收到错误The resource cannot be found。下面是代码:

$.getJSON("api/UserApi",
    function (data) {
        ...               
    });

I don't want to use an absolute URL in the code, e.g.:

我不想在代码中使用绝对 URL,例如:

$.getJSON("http://localhost/myApp/api/UserApi",          
    function (data) {
        ...    
    });

The absolute URL does work fine, but lacks flexibility. Is there a way to do the same thing as below?

绝对 URL 工作正常,但缺乏灵活性。有没有办法做与下面相同的事情?

$.getJSON("~/api/UserApi",          
    function (data) {
        ...
    });

ASP.NET supports the replacement of the "~" character with the current application's root path, e.g.:

ASP.NET 支持用当前应用程序的根路径替换“~”字符,例如:

http://localhost/myApp

http://localhost/myApp

However, the "~" character is not supported in JavaScript files. How do I accomplish the same thing?

但是,JavaScript 文件中不支持“~”字符。我如何完成同样的事情?

The JavaScript is in a standalone file that cannot use ASP.NET statements like Url.Content. Is there a better way to do it?

JavaScript 位于独立文件中,不能使用 ASP.NET 语句,如Url.Content. 有没有更好的方法来做到这一点?

I've found the following method. Are there any better solutions?:

我找到了以下方法。有没有更好的解决方案?:

1) Write the code below in a .cshtml file

1)在.cshtml文件中编写以下代码

<script type="text/javascript"> 
    var currentDomain = '@Url.Content("~")';
</script>

2) Read the currentDomainvariable from the .js file:

2)currentDomain从 .js 文件中读取变量:

$.getJSON(currentDomain + "/api/UserApi",          
    function (data) {
        ...        
});

回答by Konrad Gadzina

If you're trying to get link to an action, you can define JavaScript variales in your view that will be populated with Url.Action:

如果您尝试获取操作的链接,您可以在视图中定义 JavaScript 变量,这些变量将填充Url.Action

<script type="text/javascript">
    var userApiPath = '@(Url.Action("userApi", "api"))';
</script>

And later use this variable in your JS file:

稍后在您的 JS 文件中使用此变量:

$.getJSON(userApiPath,          
    function (data) {
});

If you want a general path to your app, you can do something like that:

如果您想要应用程序的一般路径,您可以执行以下操作:

<script type="text/javascript">
    var path = '@(string.Format("{0}://{1}{2}",
                Request.Url.Scheme,
                Request.Url.Host,
                (Request.Url.IsDefaultPort) ? "" : string.Format(":{0}",
                Request.Url.Port)))';
</script>

And later use this variable somewhere in your JS files. Of course you don't have to use string.Formatto do this, that's just an example.

稍后在您的 JS 文件中的某处使用此变量。当然,您不必使用string.Format这样做,这只是一个示例。

EDIT:

编辑:

You may also consider using RazorJS.

你也可以考虑使用RazorJS

回答by Amit

@Url.Action

for the Javascript

对于 Javascript

@Url.Content

for CSS and JS File Adding.

用于 CSS 和 JS 文件添加。

回答by Artless

Have you tried the URL helper? It allows you to generate a fully qualified URL for your controller/action, like such:

你试过URL helper吗?它允许您为控制器/操作生成完全限定的 URL,例如:

@Url.Action("Index", "Home", etc...)

Reference: MSDN

参考:MSDN

UPDATE
I noticed you were referring to writing dynamic URLs into your .js file. You shouldn't hard-code URLs into your scripts, it will make your code harder to maintain. What if you change domains tomorrow and forget to change URLs in one of the script files? You should pass the URL as a parameter to your JS function from your .cshtml page instead.

更新
我注意到您指的是将动态 URL 写入您的 .js 文件。您不应该将 URL 硬编码到您的脚本中,这会使您的代码更难维护。如果您明天更改域并忘记更改其中一个脚本文件中的 URL 怎么办?您应该将 URL 作为参数从 .cshtml 页面传递给您的 JS 函数。

回答by Aleksei

In a View set page Url:

在视图集页面 URL 中:

<script type="text/javascript">
    var PageUrl = '@Url.Action("Index","Home")';
</script>

then in a js file:

然后在一个js文件中:

function MyFunc() {
var $form = $('form[id="Form"]');
    $.ajax({
    type: 'GET',
    url: PageUrl+"/MyActionName",
    data: $form.serialize(),
    cache: false,
    error: function (xhr, status, error) {

    },
    success: function (result) {
        //do something
    }
});

}

}