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.

1

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

5 Comments

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

1 Comment

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.
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.

1 Comment

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.
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.

3 Comments

Thanx Arash! That's the only way worked for me. I had to place "ld+json" on the page.
I am happy that it was helpful for you @Aviw. you are always welcome.
BTW, just to mention, I've used this in ASP.NET MVC, so it's available not only in Core

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.