2

So I'm writing an ASP.NET MVC Web application and at the top of one of my razor pages i have this code:

    <script type="text/javascript">
        alert("@TempData["alertMessage"]");
    </script>

If I understand the error

Unterminated string constant

correctly, it means I haven't closed the quotation marks. But if I look at the code it should be closed correctly right?

What is wrong about it?

3
  • 1
    alert("@(TempData["alertMessage"])"); Commented Dec 12, 2017 at 9:18
  • This also seems to remove the error, so there's multiple correct answers. Thank you. Commented Dec 12, 2017 at 9:19
  • 1
    Possible duplicate of Escaping JavaScript string literals in views Commented Dec 12, 2017 at 9:34

1 Answer 1

4

You should use single quotes in order to avoid the error.

alert('@TempData["alertMessage"]');

With the other words you should wrap the statement within single quotes.

Sign up to request clarification or add additional context in comments.

4 Comments

Ahhhh that fixed it for me. Thank you very much!
That doesn't address the core problem which is differentiating between Razor code and HTML/JS code. Using an explicit @(...) does it well.
@haim770, thanks for your point. This problem can appear, for instance, when you append dynamically elements to page which contains attributes and you're forces to use single quotes.
This will HTML-encode the string that must be JS-encoded. Please use the correct approach instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.