Search code examples
jqueryasp.net-mvcviewbag

How to parse objects from ViewBag to JavaScript?


I am trying to parse an object from ViewBag to Javascript without luck. I have tried so far with jQuery/razor/mixed syntax...to no avail. When I tried with Json.Encode(), I get an "error not defined".

Class

class Story 
{
    public long Id {get;set;}
    public string Description{get;set;}
}

Controller

[HttpGet]
public IActionResult Index(Story _story) 
{
    List<Location> Locations = this.context.Locations.ToList();
    ViewBag.story = _story;
    return View(context.Locations);
}

View

$(document).ready(function() {
        var story = JSON.parse("@ViewBag.story");
        var story2try = '@(ViewBag.story)';

        console.log(@ViewBag.story.Id);
        console.log(story);
        console.log(story2try);
});

The thing is the first log gets printed so for primitive data types such as strings/int/long it works but not for objects. I get this error afterwards:

Unexpected token A in JSON at position 0 SyntaxError: Unexpected token A in JSON at position 0


Solution

  • So after countless tries i managed to solve the problem :

    1.Serialize my object in the controller as others pointed out using the Newtonsoft.Json library:

    ViewBag._story =JsonConvert.SerializeObject(_story);  
    

    2.In the view i would deserialize it using:

    var _story=@(Html.Raw(ViewBag._story));
    

    Thank you for your help !