asp.net mvc 4 javascript inside razor block throws error

12,141

Solution 1

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>
}

Solution 2

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).

Share:
12,141
Jack
Author by

Jack

Updated on August 04, 2022

Comments

  • Jack
    Jack over 1 year

    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!