Razor + JS Uncaught SyntaxError:无效或意外的令牌

Razor + JS Uncaught SyntaxError: Invalid or unexpected token

本文关键字:意外 令牌 无效 JS Uncaught SyntaxError Razor      更新时间:2023-09-26

我有这样的代码:

var tempPath = "@Path.GetTempPath()";
var blobURL = tempPath + "image.jpg";

当我检查我的页面时,我得到这个错误:

未捕获SyntaxError:无效或意外的令牌

这一行下划线

var tempPath = "C:'Windows'TEMP'";
这可能是一个愚蠢的解决方案,但我似乎找不到它。我希望我的blob-URL为C:'Windows'TEMP'image.png,这样我就可以像这样使用它:
<img src="C:'Windows'TEMP'image.png"/>

编辑:我不想硬核这个临时路径,因为我不知道它是否总是相同的。

下面的JavaScript是无效的:

var tempPath = "C:'Windows'TEMP'";  // look at code highlighting
console.log(tempPath); // and at the result of execution

问题是'反斜杠应该在JS字符串中转义。
您需要这样转义反斜杠:

var tempPath = "C:''Windows''TEMP''";
console.log(tempPath);

为了使用Razor实现此目的,您可以执行以下操作:

var tempPath = "@HttpUtility.JavaScriptStringEncode(Path.GetTempPath())";