DCalic DCalic - 5 months ago 63
ASP.NET (C#) Question

Razor + JS Uncaught SyntaxError: Invalid or unexpected token

I have this code:

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

I get this error when I inspect my page:

Uncaught SyntaxError: Invalid or unexpected token

And this line is underlined:

var tempPath = "C:\Windows\TEMP\";

It's probably a stupid solution but i can't seem to find it. I want my blob-URL to be C:\Windows\TEMP\image.png so i can then use it like this:

<img src="C:\Windows\TEMP\image.png"/>

I don't want to hardcore this temp path cause i have no idea if it will always be the same.


The following JavaScript is just invalid:

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

The problem is that \ backslashes should be escaped in JS strings.
You need to escape backslashes this way:

var tempPath = "C:\\Windows\\TEMP\\";

In order to achieve this using Razor, you can do the following:

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