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.
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With