Convert Object to JSON in MVC 4

前端 未结 3 1883
被撕碎了的回忆
被撕碎了的回忆 2021-02-03 21:30

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

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


        
相关标签:
3条回答
  • 2021-02-03 22:04

    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().

    0 讨论(0)
  • 2021-02-03 22:12

    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);
    }
    
    0 讨论(0)
  • 2021-02-03 22:25

    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.

    0 讨论(0)
提交回复
热议问题