1

I have a file for my javascript separate from my web pages. However what this appears to mean is that I cannot write the following line;

var url = '@Url.Action("AddTrade", "DataService")';

I am reluctant to hard code the url in case it is different when I deploy it.

So what should I do about this?

2

1 Answer 1

1

I use an object to print all the urls I'll use from the scripts. This code goes into the _Layout or any view.

Like this:

<script type="text/javascript">
    windows.Urls = {};
    window.Urls["SomeKey"] = "@Url.Action("AddTrade", "DataService")";
</script>

Then, from the scripts, you use:

var url = window.Urls["SomeKey"];
// Or even easier:
var url = Urls.SomeKey
Sign up to request clarification or add additional context in comments.

3 Comments

+1. But I cant understand fully, Could you give usage example? Where do you define, and where do you use? Thanks a lot
after edit: And, call above code in external js file like this var url = window.Urls["SomeKey"]; ? right ?
As an alternate approach, you might want to look at this answer: stackoverflow.com/a/14281042/195550

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.