How to populate javascript variable with JSON from ViewBag?
Asked Answered
T

4

27

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.

Thracian answered 26/3, 2014 at 16:18 Comment(1)
possible duplicate of ASP.NET MVC: How to convert View Model into Json objectHybris
I
52

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>
Ingeringersoll answered 26/3, 2014 at 16:31 Comment(5)
Yes, exactly. I had to to a JSON.parse because it was getting it as a string: var userInfo = JSON.parse('@Html.Raw(userInfoJson)')Thracian
you can skip the sever side serialization and just use var userInfo = JSON.parse('@Html.Raw(Json.Encode(ViewBag.User))');Annettannetta
I don't think you need to parse the json as a string. Just output var userInfo = @Html.Raw(userInfoJson)Leeland
@Annettannetta Json.Encode throws error Unexpected token however var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(model)); worked good for me.Chapeau
In the javascript: without the single quote marks did it for me. var userInfo = JSON.parse(@Html.Raw(userInfoJson));Essential
G
11

Was using this solution for simple objects. But I had some problems getting an array to js objects so I'll just leave what I did here.

C#

@{
  using Newtonsoft.Json;
  ViewBag.AvailableToday = JsonConvert.SerializeObject(list);
}

js

var availableToday = JSON.parse('@Html.Raw(ViewBag.AvailableToday)');
Geddes answered 30/1, 2015 at 11:58 Comment(1)
Hey i have been use this way but when i have property wich contains html or another json inside i get this error "Unexpected token t in JSON at position" i trying to resolve it.Pledge
P
2

Client-Side Code:

This is an ajax call to a .Net MVC Controller:

var clientStuff;

$.ajax({
    type: 'GET',
    url: '@Url.Action("GetStuff", "ControllerName")',
    data: {},
    dataType: "json",
    cache: false,
    async: false,
    success: function (data) {
        clientStuff = data;
    },
    error: function(errorMsg) {
        alert(errorMsg);
    }
});

Server-Side Code:

CONTROLLER:

    public JsonResult GetStuff()
    {
        return Json(_manager.GetStuff(), JsonRequestBehavior.AllowGet);
    }

MANAGER:

    public IEnumerable<StuffViewModel> GetStuff()
    {
        return _unitofWork.GetStuff();
    }

UNIT OF WORK:

    public IEnumerable<StuffViewModel> GetStuff()
    {
        var ds = context.Database.SqlQuery<StuffViewModel>("[dbo].[GetStuff]");
        return ds;
    }

Unit of Work can be a query to a sproc (as I have done), a repository context, linq, etc. I'm just calling a sproc here for simplicity, although it could be argued that the simplicity lies with Entity Framework and Linq.

Pekin answered 31/3, 2015 at 20:46 Comment(1)
For me this is the most elegant solution. Just one note that you want clientStuff = JSON.parse(data); to actually store the object rather than the textual representation.Marcie
A
1

You can change this line :

ViewBag.User = repo.GetUserInfo();

To

ViewBag.User = new HtmlString(repo.GetUserInfo());

You should add using Microsoft.AspNetCore.Html; or using System.Web; if HtmlString is not accessible.

Aversion answered 18/5, 2020 at 18:44 Comment(3)
Thanx Arash! That's the only way worked for me. I had to place "ld+json" on the page.Spelling
I am happy that it was helpful for you @Aviw. you are always welcome.Aversion
BTW, just to mention, I've used this in ASP.NET MVC, so it's available not only in CoreSpelling

© 2022 - 2024 — McMap. All rights reserved.