30

I am converting an object to JSON using JavaScriptSerializer and I can see this JSON output in server code:

[{"UserId":1,"UserName":"Admin"}]

But in the UI it's getting converted to something like below

[{"UserId":1,"UserName":"Admin"}].

How to escape those "?

Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74
user1735105
  • 301
  • 1
  • 3
  • 3

3 Answers3

69

If you are using the Razor view engine you need to use the Html.Raw method:

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

Notice the usage of the Json.Encode method which is shorter and equivalent to new JavaScriptSerializer().Serialize().

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

Why are you doing that? Why not just return a JsonResult?

public ActionResult MyMethod()
{
    List<ListItem> list = new List<ListItem>() {
        new ListItem() { UserId = "1", UserName = "Admin" },
        new ListItem() { UserId = "2", UserName = "JohnDoe" },
        new ListItem() { UserId = "3", UserName = "JaneDoe" }};

    return this.Json(list);
}
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • 2
    Regarding your last edit, why is it better to specify `ActionResult` as return type instead of `JsonResult`? – Yannick Blondeau Oct 10 '12 at 16:08
  • 3
    @YannickBlondeau - JsonResult *IS* an ActionResult. I prefer the return type to be the most general that is acceptable in order to reduce coupling. For example, if you decide to change the return type to XML, you can do so without having to also change the return type. Just my personal policy. – Erik Funkenbusch Oct 10 '12 at 18:55
0

Just one more thing on Darin Dimitrov's answer. In my VS2012 there is a compilation error with the semicolon, cuz the statement from JS side is actually "var model = ;". A way around using a pair of quotation to wrap the Razor part like this:

var model = "@Html.Raw(Json.Encode(Model))";

This will not cause any error.

Json.Encode() seems to be a wrapper function of JavaScriptSerializer. I'm not sure if the latter is more time efficient.

Fenwick
  • 1,061
  • 2
  • 15
  • 28