Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative URL inside $ajax with asp.net mvc 3

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.

like image 457
sarsnake Avatar asked Dec 19 '11 21:12

sarsnake


1 Answers

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
    });
});
like image 180
Darin Dimitrov Avatar answered Oct 05 '22 02:10

Darin Dimitrov