Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 4 javascript inside razor block throws error

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!

like image 679
Jack Avatar asked Jan 20 '13 17:01

Jack


People also ask

Can I use Razor code in JavaScript in ASP.NET MVC?

Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.

Can I use JavaScript in razor pages?

You can call JavaScript methods from the Blazor pages with the help of JavaScript Interop by injecting the dependency IJSRuntime into the razor page. Then refer the script in the HTML page of the blazor application. Check this link for more information.

Where do you put JavaScript on a razor page?

A JS file for the Index component is placed in the Pages folder ( Pages/Index. razor. js ) next to the Index component ( Pages/Index. razor ).

Can you mix MVC and Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.


2 Answers

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>
}
like image 200
Martin Avatar answered Sep 28 '22 09:09

Martin


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

like image 43
Ely Avatar answered Sep 28 '22 10:09

Ely