Asp.Net-Mvc: Razor '@' Symbol in Js File

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="@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.

Using Razor within JavaScript

Use the <text> pseudo-element, as described here, to force the Razor compiler back into content mode:

<script type="text/javascript">

// Some JavaScript code here to display map, etc.

// Now add markers
@foreach (var item in Model) {
<text>
var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
var title = '@(Model.Title)';
var description = '@(Model.Description)';
var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

var infowindow = new google.maps.InfoWindow({
content: contentString
});

var marker = new google.maps.Marker({
position: latLng,
title: title,
map: map,
draggable: false
});

google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
</text>
}
</script>

Update:

Scott Guthrie recently posted about @: syntax in Razor, which is slightly less clunky than the <text> tag if you just have one or two lines of JavaScript code to add. The following approach would probably be preferable, because it reduces the size of the generated HTML. (You could even move the addMarker function to a static, cached JavaScript file to further reduce the size):

<script type="text/javascript">

// Some JavaScript code here to display map, etc.
...
// Declare addMarker function
function addMarker(latitude, longitude, title, description, map)
{
var latLng = new google.maps.LatLng(latitude, longitude);
var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

var infowindow = new google.maps.InfoWindow({
content: contentString
});

var marker = new google.maps.Marker({
position: latLng,
title: title,
map: map,
draggable: false
});

google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}

// Now add markers
@foreach (var item in Model) {
@:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
}
</script>

Updated the above code to make the call to addMarker more correct.

To clarify, the @: forces Razor back into text mode, even though addMarker call looks a lot like C# code. Razor then picks up the @item.Property syntax to say that it should directly output the contents of those properties.

Update 2

It's worth noting that View code really isn't a good place to put JavaScript code. JavaScript code should be placed in a static .js file, and then it should get the data that it needs either from an Ajax call or by scanning data- attributes from the HTML. Besides making it possible to cache your JavaScript code, this also avoids issues with encoding, since Razor is designed to encode for HTML, but not JavaScript.

View Code

@foreach(var item in Model)
{
<div data-marker="@Json.Encode(item)"></div>
}

JavaScript code

$('[data-marker]').each(function() {
var markerData = $(this).data('marker');
addMarker(markerData.Latitude, markerData.Longitude,
markerData.Description, markerData.Title);
});

Is it possible to use razor syntax in Javascript files?

I found a razor engine RazorJS on nuget that solves @ in js files

The owner blog and explanations about the package abilities

The Nuget package

see more in this question

How To use @ symbol in jquery in mvc

You can type it twice as shown below:

if (password.match(/(.*[!,%,&,@@,#,$,^,*,?,_,~].*[!,%,&,@@,#,$,^,*,?,_,~])/)) {
alert('yes');
strength += 1
}

Since @ is a special character for razor syntax. You can escape it by typing another @

UPDATE

Since you are trying it in regex and as mentioned, @@ just solves the compilation error but gives wrong results while using the regex, please try:

if (password.match(/(.*[!,%,&,@('@'),#,$,^,*,?,_,~].*[!,%,&,@('@'),#,$,^,*,?,_,~])/)) {
alert('yes');
strength += 1
}

The @('@') will be converted into @ by razor and should give you the desired result.

@ symbol in JavaScript block

This is a feature of the Razor view engine - it handles the switch between HTML/Javascript and your server-side view code so you don't need to escape it in most cases.

See Scott Guthrie's blog post on it: http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx

Razor ViewEngine: How do I escape the @ symbol?

You have to use @@ to escape the @ symbol.

One important thing to notice is that you DO NOT need to escape the @ symbol when it exists within an email address. Razor should be smart enough to figure that out on its own.

Escape @ character in razor view engine

@@ should do it.

Razor Syntax and Javascript

You need to wrap it in the pseudo element <text>. This will switch the parser back to html mode and it will then parse the javascript as part of the html and not c#. The reason it happens is the @for() is a c# block and anything treated within is also considered c# until it's escaped by an html tag. Since you probably don't want an html tag razor provides the <text> tag to switch modes.

If you notice the difference in your asp.net webforms you end the <% for line with a %> which takes it out of c# mode. If you download the razor highlighter extension for visual studio 2010 it will help you see when code is treated as code and html is treated as html.

<script type="text/javascript">
var jqGridIdList = "@Url.Action("getidlist", "office", new { area = "reports" })";

var availableIds = [];
@for(var i = 0; i < Model.Data.Count (); i++) {
<text>availableIds.push({ value : "@Model.Data.ElementAt(i).Text", label : "@Model.Data.ElementAt(i).Text" });</text>
}
</script>

Update for latest version

You can now use the @: syntax for even more readability

<script type="text/javascript">
var jqGridIdList = "@Url.Action("getidlist", "office", new { area = "reports" })";

var availableIds = [];
@for(var i = 0; i < Model.Data.Count (); i++) {
@:availableIds.push({ value : "@Model.Data.ElementAt(i).Text", label : "@Model.Data.ElementAt(i).Text" });
}
</script>

What does @: mean in ASP.net MVC Razor?

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

Example:

@foreach (TestClass item in Model)
{
@:@item.Code - @item.Name
}

Without the @: it wouldn't be possible to do this, since all the chars after the first @ will be considered as C#.

This way you are saying that you are getting the two variables from item and placing the char - between them and the result is a content block (or html/text)

Difference between script src and code inside script in asp.net mvc 3 razor partial view executing jquery.ajax

Try following:

<script type="text/javascript" src="path to my script file">



Related Topics



Leave a reply



Submit