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 can't.
In MVC, @ is the respective char that allows you to use razor inside HTML (inside a . cshtml) which in runtime (or precompiled) will be converted to c#. With @ you may write C# within HTML and with @: you may write HTML within C#.
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.
Well I've just found a razor engine on nuget that does it! Meaning solves @
syntax!
It's name is RazorJS.
The Nuget package
2016 Update:
The package wasn't updated for 5 years, and the project site link is dead. I do not recommend people to use this library anymore.
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