I have a .csHtml
-razor file with a javascript function that uses the @Url.Content
C# function inside for the ajax URL.
I want to move that function to a .js
file referenced from my view.
The problem is that javascript doesn't "know" the @
symbol and doesn't parse the the C# code.
Is there a way to reference .js
files from view with "@" symbol?
You could use HTML5 data-*
attributes. Let's suppose that you want to perform some action when some DOM element such as a div is clicked. So:
<div id="foo" data-url="@Url.Content("~/foobar")">Click me</div>
and then in your separate javascript file you could work unobtrusively with the DOM:
$('#foo').click(function() {
var url = $(this).data('url');
// do something with this url
});
This way you could have a pure separation between markup and script without you ever needing any server side tags in your javascript files.