How to populate javascript variable with JSON from ViewBag?

empz picture empz · Mar 26, 2014 · Viewed 43.7k times · Source

I have this Index action:

public ActionResult Index()
{  
    var repo = (YammerClient) TempData["Repo"];
    var msgCol = repo.GetMessages(); 

    ViewBag.User = repo.GetUserInfo();
    return View(msgCol.messages);
}

GetMessages returns a list of POCO messages and GetUserInfo returns a POCO with the info of the user (id, name, etc).

I want to fill a javascript variable with the JSON representation of the user info.

So I would want to do something like this in the view:

...
<script>
    var userInfo = "@ViewBag.User.ToJson()"
</script>
...

I know that doesn't work, but is there a way to do that? I want to avoid having to do an ajax request once the page is loaded just to get the user info.

Answer

sanjeev picture sanjeev · Mar 26, 2014

In View you can do something like this

@{
        var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        var userInfoJson = jss.Serialize(ViewBag.User);
}

in javascript you can use it as

<script>


    //use Json.parse to convert string to Json
    var userInfo = JSON.parse('@Html.Raw(userInfoJson)');
</script>