首页 > 解决方案 > 如何从传递给视图的模型访问 javascript 文件中的 json 对象

问题描述

我的数据库中有一个 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 字符串,但我得到了一个对象(?),我很困惑如何从中解码 html,然后将生成的 json obejct 转换为要在 javascript 文件中读取的 json 字符串。任何帮助都会很棒!

标签: javascriptjsonrazormodel-view-controller

解决方案


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'];

推荐阅读