Relative url inside $ ajax with asp.net mvc 3

I know that this function can be used

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

to avoid hard-coding URLs, but my $.ajax calls are in a separate .js file. Will the above still work?

As far as I know, @Url.Action will only work inside the Razor file. But, given that we are encouraged to use unobtrusive JS, I'm not quite sure how to use @Url.Action .

Please inform.

+6
source share
2 answers

Will the above still work?

Not.

As far as I know, @ Url.Action will only work inside the Razor file

Your knowledge is correct.

But, given that we are encouraged to use unobtrusive JS, I'm not quite sure how I will use @ Url.Action.

You can use the HTML5 data- * attributes for some DOM element that you are unobtrusively improving (if this element is no longer a <form> or an anchor, in this case it already contains a 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 }); }); 
+12
source

Add function parameter for relative paths. For example, 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
source

Source: https://habr.com/ru/post/904113/


All Articles