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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
empz
  • 11,509
  • 16
  • 65
  • 106
  • possible duplicate of [ASP.NET MVC: How to convert View Model into Json object](http://stackoverflow.com/questions/3365551/asp-net-mvc-how-to-convert-view-model-into-json-object) – alexmac Mar 26 '14 at 16:29

4 Answers4

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>
sanjeev
  • 1,407
  • 2
  • 18
  • 30
  • 1
    Yes, exactly. I had to to a JSON.parse because it was getting it as a string: `var userInfo = JSON.parse('@Html.Raw(userInfoJson)')` – empz Mar 26 '14 at 16:39
  • 7
    you can skip the sever side serialization and just use `var userInfo = JSON.parse('@Html.Raw(Json.Encode(ViewBag.User))');` –  Jan 31 '15 at 04:49
  • 2
    I don't think you need to parse the json as a string. Just output `var userInfo = @Html.Raw(userInfoJson)` – Ally Mar 01 '16 at 02:46
  • @user3559349 Json.Encode throws error _Unexpected token_ however `var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(model));` worked good for me. – sairfan May 01 '19 at 16:53
  • In the javascript: without the single quote marks did it for me. var userInfo = JSON.parse(@Html.Raw(userInfoJson)); – M.Qudah Apr 27 '23 at 13:57
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)');
KnuturO
  • 1,565
  • 15
  • 19
  • 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. – Richard Aguirre Nov 28 '17 at 20:32
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.

eilenberger
  • 469
  • 4
  • 2
  • 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. – Rich Aug 17 '15 at 09:33
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.

Aviw
  • 1,056
  • 11
  • 14
Arash.Zandi
  • 1,010
  • 2
  • 13
  • 24