6

I know one can use this function

@Url.Action("MyInfo", "Home")

to avoid the hardcoding of urls, but my $.ajax calls are in a separate .js file. Would the above still work?

From my knowledge, the @Url.Action will only work inside the Razor file. But considering that we are advised to use non-obtrusive JS, I am not quite sure how I would use the @Url.Action.

Please advise.

2 Answers 2

12

Would the above still work?

No.

From my knowledge, the @Url.Action will only work inside the Razor file

Your knowledge is correct.

But considering that we are advised to use non-obtrusive JS, I am not quite sure how I would use the @Url.Action.

You could use HTML5 data-* attributes on some DOM element that you are unobtrusively enhancing (unless this element is already a <form> or an anchor in which case it already contains an url):

<div id="foo" data-url="@Url.Action("foo")">Hello</div>

and then in your separate javascript file:

$(function() {
    $('#foo').click(function() {
        var url = $(this).data('url');
        // TODO: do something with the url
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

If you have a form already just do this: var url = $('form').url;.
4

Add a function parameter for the relative paths. E.g., in your View:

<script type="text/javascript">
   var path =  "@Url.Action("ActionName", "ControllerName")";

   someAjaxMethod(path)
</script>

and in your external js file:

function someAjaxMethod(path)
{
   var data = {};
   $.ajax(path, data)
}

4 Comments

This example doesn't show a good approach, because path variable is now global. It would be better to use some namespacing for global URLs or "data-url" approach for local urls
I agree it's not the best answer, and I prefer @Darin's approach, but it's still valid for simple scenarios.
Sorry, but you rollbacked my edit with real improvements to the code that even doesn't work (syntax error)? I would downvote twice if I could. You can write any code you won't but no one should ever copy it!
Wow. If you think it's so bad, then write your own answer. I'm not sure why it even matters since there's another accepted answer.

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.