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,882
  • 13
  • 71
  • 101
Richard Tasker
  • 244
  • 2
  • 12
  • 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
  • 868,454
  • 176
  • 1,908
  • 1,964
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
  • 28,238
  • 6
  • 56
  • 88
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
  • 305,182
  • 66
  • 621
  • 471