0

I would like to print a json literal inside of an cshtml page (razor), I want to populate a json object in javascript and be ready when the page load, and not wait until the page load and then make an ajax call.

What I'm trying to do is something like

/*Some view*/

@{
    ViewBag.Title = "Some title";         

}
<script>
    _SERVER_["someVar"] ="@SomeClass.Models.MovimientosMotivosModel.getMyarray()";
</script>

The problem is when I try to serialize the json all the double quotes get replace be html encoding and my json became a mess... how can achieved this?

ncubica
  • 8,169
  • 9
  • 54
  • 72
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Feb 21 '13 at 21:51
  • Mmm ok can be duplicated but I didn't find this answer looking on google either using literal or encoding as word search. – ncubica Feb 21 '13 at 21:59

1 Answers1

3

Use the Json.Encode method:

<script>
    _SERVER_["someVar"] = @Html.Raw(Json.Encode(SomeClass.Models.MovimientosMotivosModel.getMyarray()));
</script>

This will ensure that the server side value is properly encoded to a javascript object that you could access on the client. The @Html.Raw method on the other hand will not HTML encode it as the standard @ Razor function does.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928