9

This is my razor code which throws error:

@section script
{
    <script type="text/javascript">
        $(document).ready(function () {
            @if (TempData["Message"] != null)
            {
                showNotification("'" + TempData["Message"].ToString() + "'");
            }
        });
    </script>
}

It says showNotification doesn't exist. It thinks this is a C# code where it's a javascript function. Could anybody please let me know how do I fix this error? Thanks!

2
  • I know this isn't the answer, and that people will show you one of the many ways to fix this (@: syntax for one). I'd just remove the @if statement completely, and not call ToString() explicitly but let it be called implicitly. That'd work Commented Jan 20, 2013 at 17:59
  • The problem with TempData is that if the TempData["Foo"] is null, then u get a NPE. so use ViewBag Commented Jan 20, 2013 at 18:00

2 Answers 2

18

Throw a text tag around it, since the compiler thinks your JavaScript is Razor syntax. When you do this, you will need to add a @ to the TempData call.

@section script
{
    <script type="text/javascript">
        $(document).ready(function () {
            @if (TempData["Message"] != null)
            {
                <text>showNotification('@TempData["Message"].ToString()');</text>
            }
        });
    </script>
}
Sign up to request clarification or add additional context in comments.

Comments

6

In addition to @Martin's answer, you can also put @: in front of the showNotification call. The @: syntax tells Razor to treat that single line as HTML, where the tells Razor to treat anything within the text tag as HTML (useful for multi line, where @: is good for single line).

Comments

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.