我通过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();
}
答案 0 :(得分:7)
由于它是一个字符串值,您需要将其包装在单引号或双引号中。
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>