0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I have a $(document).ready(function () in the js file and its here the funtion is executed. If I place alternative 2 in my $(document).ready(function () on the aspx page, will this be executed fista always?
It depends if you included your js files before you placed the $(document).ready or after. anyway, you don't have to use $(document).ready in your aspx just to set a global variable, it's not a thing you want to happen only after the entire page is loaded. just make the assignment before you include you js file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.