8

The below line appears in one of my javascript files, what would be the syntax for it in Razor.

var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
Jeff LaFay
  • 12,424
  • 13
  • 71
  • 98
Richard Tasker
  • 244
  • 2
  • 11
  • You should be able to just use `var initialData = @new JavaScriptSerializer().Serialize(Model);`, but I haven't begun using Razor for real yet, so I'm not sure. – Tomas Aschan Feb 25 '11 at 17:42
  • 1
    @Tomas: No; you need to wrap it in parentheses, to force the parser to read past the space. – SLaks Feb 25 '11 at 17:43
  • @SLaks: Ah! Well, there's a reason I said that in a comment and not in an answer =) – Tomas Aschan Feb 25 '11 at 18:26

3 Answers3

22

Like this:

@Html.Raw(new JavaScriptSerializer().Serialize(Model))

The Html.Raw call is necessary to prevent it from being HTML-escaped.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
7

For a more succinct feel, you can use the Web Pages Json helper's Encode method:

var initialData = @Html.Raw(Json.Encode(Model))
Mike Brind
  • 25,035
  • 6
  • 49
  • 82
1

If you want the serialized JavaScript to properly support DateTime, use the serializer from Json.NET instead. According to this post, even Microsoft uses this for serialization with MVC4.

var initialData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
Community
  • 1
  • 1
JohnnyHK
  • 290,447
  • 61
  • 595
  • 453