【问题标题】:ASP.NET Core ViewData access in javascriptjavascript 中的 ASP.NET Core ViewData 访问
【发布时间】:2017-05-14 20:42:45
【问题描述】:

我正在通过 ViewData 从控制器向 html 页面发送一个文件路径(字符串),我想在我的 javascript 中访问该字符串,使用它,在 javascript 中运行一些算法,然后使用结果来使用它们并在相同的 html 页面。

HTML

</head>
<body>
    <div id="mychart"></div>
    <script>
        var path=@ViewData["path"];
        //some javascript logic with the string path of the file.
        //using results for output chart of id 'mychart'
    </script>
</body>
</html>

控制器动作代码:

        public IActionResult CellResult(string outputpath)
        {
            ViewData["path"] = outputPath;
            return View();
        }

【问题讨论】:

    标签: javascript html asp.net viewdata


    【解决方案1】:

    由于是字符串值,所以需要用单引号或双引号括起来。

    var path='@ViewData["path"]';
    alert(path);
    

    编辑:根据评论

    如何将字符串列表从控制器发送到 html 页面并使用 它在javascript中?而不是字符串,我想发送一个字符串列表

    如果你想发送一个字符串列表,也是一样的,但是由于现在是复杂类型,你需要使用json序列化器将这个对象转换为字符串。

    所以在你的服务器中

    var list = new List<string> {"Hi", "Hello"};
    ViewBag.MyList = list;
    

    在视图中

    <script>
        var list = @Html.Raw(JsonConvert.SerializeObject(ViewBag.MyList));
        console.log(list);
    </script>
    

    【讨论】:

    • 你能告诉我如何将字符串列表从控制器发送到 html 页面并在 javascript 中使用它吗?而不是字符串我想发送一个字符串列表
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2011-01-23
    • 2019-02-03
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多