ASP.NET javascript 中的核心 ViewData 访问

ASP.NET Core ViewData access in javascript

我正在通过 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();
        }

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

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

编辑: 根据评论

How can I send a list of string from controller to html page and use it in javascript? instead of string i wanna send a list of string

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

所以在你的服务器中

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

并在视图中

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