asp.net mvc 4 javascript inside razor block throws

2020-06-17 05:24发布

问题:

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!

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


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