asp.net-mvc: razor ‘@’ symbol in js file

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="https://stackoverflow.com/questions/7902213/@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.

Leave a Comment