如何将对象从ViewBag解析为JavaScript? [英] How to parse objects from ViewBag to JavaScript?

查看:132
本文介绍了如何将对象从ViewBag解析为JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ViewBag中的对象解析为Javascript,但是没有运气.到目前为止,我已经尝试使用jQuery/razor/混合语法...无济于事.当我尝试使用Json.Encode()时,出现未定义错误".

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 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);
});

问题是第一个日志被打印出来,因此对于原始数据类型(例如字符串/整数/长整数)有效,但对对象则无效.之后我收到此错误:

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:

位置0的JSON中的意外令牌A SyntaxError:位置0的JSON中的意外令牌A

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

推荐答案

因此,在无数次尝试之后,我设法解决了这个问题:

So after countless tries i managed to solve the problem :

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

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

ViewBag._story =JsonConvert.SerializeObject(_story);  

2 .在视图中,我将使用以下方法反序列化它:

2.In the view i would deserialize it using:

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

谢谢您的帮助!

这篇关于如何将对象从ViewBag解析为JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆