简体   繁体   中英

@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. 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.

$(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";' was executed the 'url' was set to "@Url.Content("~/")GetMeters".

Looking at similar issues on StackOverflow, so I tried just using "~/GetMeters" and it doesn't work either.

If the url is set to ' https://localhost:44344/Meters/GetMeters ' my function on the controller will get called correctly. 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 ). Nothing else goes through the Razor view engine, so it can't be expected to work in any file other than a CSHTML file.

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. For your particular case, it seems you just need to pass a URL root to the script so it can call an endpoint. It is usually best to fully render action URLs server-side instead of building them client-side, if possible. To do this, you can use one of the following.

1. Provide a global variable from the view that references this file

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

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

2. Have the script expose a function and call it from the view

somescript.js

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

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.

Example :

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

You only need to use the websiteUrl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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