Is it possible or is there a workaround to use Razor syntax within JavaScript that is in a view (cshtml
)?
I am trying to add markers to a Google map... For example, I tried this, but I'm getting a ton of compilation errors:
<script type="text/javascript">
// Some JavaScript code here to display map, etc.
// Now add markers
@foreach (var item in Model) {
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);
});
}
</script>
I finally found the solution (*.vbhtml):
I just wrote this helper function. Put it in
App_Code/JS.cshtml
:Then in your example, you can do something like this:
Notice how I don't put quotes around it. If the title already contains quotes, it won't explode. Seems to handle dictionaries and anonymous objects nicely too!
A simple and a good straight-forward example:
This creates a script in your page at the location you place the code above which looks like the following:
Now you have a global JavaScript variable named
razorUserName
which you can access and use on the client. The Razor engine has obviously extracted the value from@User.Identity.Name
(server-side variable) and put it in the code it writes to your script tag.What specific errors are you seeing?
Something like this could work better:
Note that you need the magical
<text>
tag after theforeach
to indicate that Razor should switch into markup mode.The following solution seems more accurate to me than combine JavaScript with Razor. Check this out: https://github.com/brooklynDev/NGon
You can add almost any complex data to ViewBag.Ngon and access it in JavaScript
In the controller:
In JavaScript:
It's allows any plain old CLR objects (POCOs) that can be serialized using the default
JavascriptSerializer
.That will work fine, as long as it's in a CSHTML page and not an external JavaScript file.
The Razor template engine doesn't care what it's outputting and does not differentiate between
<script>
or other tags.However, you need to encode your strings to prevent XSS attacks.