Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 272
gdoron is supporting Monica Avatar asked Oct 26 '11 11:10

gdoron is supporting Monica


People also ask

Can I use Razor code in Javascript in ASP NET MVC?

You can't.

What does the at symbol mean in MVC?

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#.


2 Answers

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.

like image 124
Darin Dimitrov Avatar answered Oct 10 '22 22:10

Darin Dimitrov


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.

like image 31
gdoron is supporting Monica Avatar answered Oct 10 '22 22:10

gdoron is supporting Monica