Question

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.

Was it helpful?

Solution

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>

OTHER TIPS

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)');

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top