如何将对象从 ViewBag 解析为 JavaScript?

How to parse objects from ViewBag to JavaScript?

我正在尝试将一个对象从 ViewBag 解析为 Javascript,但不幸的是。到目前为止,我已经尝试使用 jQuery/razor/mixed 语法......无济于事。当我尝试使用 Json.Encode() 时,我得到一个 "error not defined".

Class

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

控制器

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

查看

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

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

问题是第一个日志被打印出来,因此对于 strings/int/long 这样的原始数据类型,它可以工作,但不适用于对象。之后我收到此错误:

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

有必要先序列化模型对象(就像评论中建议的那样)然后获取其原始内容(检查 ASP.NET MVC using ViewData in javascript 线程),例如:

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

$(function () {
    var story = @Html.Raw(ViewBag.story);
    alert(story.Id);
});

经过无数次尝试,我终于解决了这个问题:

1。在控制器中序列化我的对象,正如其他人使用 Newtonsoft.Json 库指出的那样:

ViewBag._story =JsonConvert.SerializeObject(_story);  

2。在视图中我将反序列化它使用:

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

感谢您的帮助!