简体   繁体   English

@ Url.Content(“〜/”)在JavaScript文件中不起作用?

[英]@Url.Content(“~/”) not working in JavaScript file?

I have an ASP.NET CORE MVC application and I am including a JavaScript file in one of my views. 我有一个ASP.NET CORE MVC应用程序,并且在其中一个视图中包含一个JavaScript文件。 The JavaScript is for a drop-down on the page that calls a function on the controller to get the data for the drop-down. JavaScript用于页面上的下拉菜单,该页面调用控制器上的函数以获取该下拉菜单的数据。

$(document).ready(function() {

    $('#accounts').change(function() {
        var url = '@Url.Content("~/")' + "GetMeters";
        var ddlsource = "#accounts";

        $.getJSON(url,
            { accountId: $(ddlsource).val() },
            function(data) {
                var items = '';
                $("#meters").empty();
                $.each(data,
                    function(i, meter) {
                        items += "<option value='" + meter.value + "'>" + meter.text + "</option>";
                    });
                $('#meters').html(items);
            });
    });

});

Stepping through the code, I noticed that after 'var url = '@Url.Content("~/")' + "GetMeters";' 逐步执行代码,我注意到在'var url ='@ Url.Content(“〜/”)'+“ GetMeters”;'之后 was executed the 'url' was set to "@Url.Content("~/")GetMeters". 执行后,“ url”设置为“ @ Url.Content(“〜/”)GetMeters“。

Looking at similar issues on StackOverflow, so I tried just using "~/GetMeters" and it doesn't work either. 看着StackOverflow上的类似问题,所以我尝试仅使用“〜/ GetMeters”,它也不起作用。

If the url is set to ' https://localhost:44344/Meters/GetMeters ' my function on the controller will get called correctly. 如果将URL设置为“ https:// localhost:44344 / Meters / GetMeters ”,则会正确调用控制器上的函数。 What's the best way to resolve this? 解决此问题的最佳方法是什么? Thank you! 谢谢!

@Url.Content is a Razor interpolation directive, and will only ever be parsed in a Razor view or page file ( .cshtml ). @Url.Content是Razor插值指令,并且只会在Razor视图或页面文件( .cshtml )中进行解析。 Nothing else goes through the Razor view engine, so it can't be expected to work in any file other than a CSHTML file. Razor视图引擎没有其他功能,因此不能期望它在CSHTML文件以外的任何文件中都可以工作。

There are several ways to pass server-side data to a JavaScript file at page load-time - more than could be covered in a StackOverflow answer. 有多种方法可以在页面加载时将服务器端数据传递到JavaScript文件-这在StackOverflow答案中已经介绍过。 For your particular case, it seems you just need to pass a URL root to the script so it can call an endpoint. 对于您的特定情况,似乎只需要将URL根传递给脚本,以便它可以调用终结点。 It is usually best to fully render action URLs server-side instead of building them client-side, if possible. 通常最好是在服务器端完全呈现操作URL,而不是在客户端构建它们。 To do this, you can use one of the following. 为此,可以使用以下方法之一。

1. Provide a global variable from the view that references this file 1.从引用此文件的视图中提供一个全局变量

SomeView.cshtml SomeView.cshtml

<script>
window.Routes = {
    getMeters: '@Url.Action("GetMeters", "Meters")', // the GetMeters action on MetersController
    // add other routes here
};
</script>

<script src="@Url.Content("~/somescript.js")"></script>

somescript.js somescript.js

$(document).ready(function() {
    var url = Routes.getMeters;
    // ...
});

2. Have the script expose a function and call it from the view 2.让脚本公开一个函数并从视图中调用它

somescript.js somescript.js

// This function replaces $(document).ready(...)
function initialize(getMetersRoute) {
    var url = getMetersRoute;
    // ...
}

SomeView.cshtml SomeView.cshtml

<script src="@Url.Content("~/somescript.js")"></script>

<script>
$(document).ready(function() {
    initialize('@Url.Action("GetMeters", "Meters")');
});
</script>

One solution is to create a variable that containt your url in a layout cshtml file that is used everywhere you use your javascript file, then you can simply call this varible in your JS file. 一种解决方案是在布局cshtml文件中创建一个包含您的url的变量,该变量在您使用javascript文件的任何地方都将使用,然后您可以在JS文件中简单地调用此变量。

Example : 范例:

websiteUrl = '@Url.Content("~/")';

You only need to use the websiteUrl. 您只需要使用websiteUrl。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM