简体   繁体   中英

ASP.NET MVC tags in a javascript?

Hi,

I need to extract a proper URL for a AJAX call and this is what I have added in my js file :

var GetLocationByParentPath = '<%= Url.Content("~/Location/GetLocationsByParent") %>';

The ASP.NET MVC tag will however not run so now is the question, how do I fill the GetLocationByParentPath with the correct value?

BestRegards

You're problem is that you're trying to accomplish something that is not supported, you cannot use C# code inside js files.

However, you can do it in your aspx files (or cshtml) and the js file can communicate with those, so you have 3 options:

1 . Add a parameter to your function in your js file that accepts the url

inside the js:

function yourfunction(url)
{
    var GetLocationByParentPath = url;
}

inside your aspx:

<script>
    yourfunction('<%= Url.Content("~/Location/GetLocationsByParent") %>');
</script>

2 . Add a global js variable that contains this url:

inside your aspx:

<script>
    var getLocationsUrl = '<%= Url.Content("~/Location/GetLocationsByParent") %>'
    yourfunction();
</script>

inside the js (make sure to define getLocationsUrl before your function runs):

function yourfunction()
{
    var GetLocationByParentPath = getLocationsUrl ;
}

3 . Use the full hard-coded url (bad for refactoring but simple solution:

inside the js (make sure to define getLocationsUrl before your function runs):

    var GetLocationByParentPath = '/Location/GetLocationsByParent';

Hope this helpes

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