How to use a server side variable in javascript with Razor
I have a piece of code in a view as
@if (Model.Count() > 0)
{
var locations = new List<string>();
var count = 1;
foreach (var shop in Model)
{
locations.Add(string.Format(
@"{{
title: ""Shop Name: {0}"",
position: new google.maps.LatLng({1}, {2}),
icon: ""{3}""
}}",
shop.ShopName,
shop.Location.Latitude,
shop.Location.Longitude,
开发者_StackOverflow中文版 count
)
);
count++;
}
var locationsJson = "[" + string.Join(",", locations.ToArray()) + "]";
}
How can I assign the locationsJson to a javascript variable as
<script type="text/javascript">
var jsLocations = @locationsJson;
</script>
Perform your embedded server code ON the server side instead, and then you could make it a property of the model and do something like:
<script type="text/javascript">
var jsLocations = @Model.locationsJson;
</script>
I have a piece of code in a view as
You absolutely should never have such piece of code in your view. Try this (shorter, better, safer):
<script type="text/javascript">
var jsLocations = @Html.Raw(Json.Encode(Model));
$.each(jsLocations, function(index, item) {
// TODO: do something with the item, for example
// alert(item.ShopName); or alert(Location.Latitude);
});
</script>
Your code will work fine.
However, you need to escape the values in your JSON, or you'll have an XSS hole.
You should use a real JSON serializer.
精彩评论