0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152
  • What does the rendered – as seen by the browser – view look like. – Richard Dec 30 '17 at 09:42
  • 1
    `'@(ViewBag.story)'` will likely give you something like `Story` - ie the type.ToString(). Your controller is returning an *object* not JSON, so there's nothing parse. You should be able to just use `var story = {}; story.Description = '@ViewBag.story.Description'; story.Id = @ViewBag.story.Id;` – freedomn-m Dec 30 '17 at 10:09
  • Did you try: `var story=JSON.parse("@((new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(ViewBag.Story))";` – freedomn-m Dec 30 '17 at 10:11
  • @Richard : i get the name of the type rendered – Bercovici Adrian Dec 30 '17 at 10:13
  • @freedomn-m so basically i have to take property by property to get all the object? And no i didn't try System.Web.Script... – Bercovici Adrian Dec 30 '17 at 10:14
  • No, that's just an example to show how to get to specific properties. If you want to *de*serialise something, you have to *serialise* it first (as per my 2nd comment). – freedomn-m Dec 30 '17 at 12:18

2 Answers2

2

It is necessary to serialize the model object first (like it is suggested in comments) plus get its raw content (check the ASP.NET MVC using ViewData in javascript thread), for example:

ViewBag.story = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_story);

$(function () {
    var story = @Html.Raw(ViewBag.story);
    alert(story.Id);
});
Mikhail
  • 9,186
  • 4
  • 33
  • 49
2

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 !

Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152