Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate javascript variable with JSON from ViewBag?

Tags:

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.

like image 632
empz Avatar asked Mar 26 '14 16:03

empz


Video Answer


1 Answers

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> 
like image 107
sanjeev Avatar answered Sep 21 '22 22:09

sanjeev