I'm trying to write an object as JSON to my Asp.Net MVC View using Razor, like so:
<script type="text/javascript">
var potentialAttendees = @Json.Encode(Model.PotentialAttendees);
</script>
The problem is that in the output the JSON is encoded, and my browser doesn't like it. For example:
<script type="text/javascript">
var potentialAttendees = [{"Name":"Samuel Jack"},];
</script>
How do I get Razor to emit unencoded JSON?
You do:
In releases earlier than Beta 2 you did it like:
Using Newtonsoft
Newtonsoft's
JsonConvert.SerializeObject
does not behave the same asJson.Encode
and doing what @david-k-egghead suggests opens you up to XSS attacks.Drop this code into a Razor view to see that using
Json.Encode
is safe, and that Newtonsoft can be made safe in the JavaScript context but is not without some extra work.See also: