繁体   English   中英

如何从传递给视图的模型访问 javascript 文件中的 json 对象

[英]How to access a json object in javascript files from a model passed to the view

我的数据库中有一个 JSON 对象,其中包含 html。 我将对象作为模型的一部分传递给我的视图。 我需要访问该对象并在页面的 javascript 文件中读取它。 但是,当我尝试将对象分配给我的 html 文件中的全局变量时,我无法在我的 javascript 文件中访问它。

我尝试将对象作为字符串读取,它返回解码后的 html(“page-1”:),我对此无能为力。 如果我调用 @Html.Raw(@Model.CourseContent.ExpectedResult) 它会按预期创建 JSON 对象。 但是在我的 javascript 文件中它被列为未定义。 我不知道如何解决这个问题。

@model DataTransferObjects.Models.UserCourseAndContent
<script>
    var totalPages = '@Model.CourseContent.TotalPages';
    var expectedResults = @HTML.Raw(@Model.CourseContent.ExpectedResult)

</script>

当我使用上面的代码时出现的 json 对象看起来像

var expectedResults = {
    "page-1": "<head></head><body></body>",
    "page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome 
                    to my news article, you’ll find some cool news here.</p> 
    <Our most recent 
    news</<p>Below you’ll find my most recent news!</p></body>"
    };

我希望它是一个实际的 json 字符串,但我得到了一个对象(?) 任何帮助都会很棒!

var expectedResults = {
    "page-1": "<head></head><body></body>",
    "page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome 
                    to my news article, you’ll find some cool news here.</p> 
    <Our most recent 
    news</<p>Below you’ll find my most recent news!</p></body>"
    };

// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));

// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM