Asp.net mvc 4 javascript inside razor block throws an error

This is my razor code that is causing the error:

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

He says showNotification does not exist. He thinks this is C # code, where he is a javascript function. Can someone please let me know how can I fix this error? Thanks!

+7
source share
2 answers

Add a text tag around it, as the compiler considers your JavaScript to be Razor syntax. When you do this, you need to add @ to the TempData call.

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

In addition to @Martin's answer, you can also put @: before calling showNotification. The @: syntax tells Razor to treat this single line as HTML, where Razor tells it to treat anything in the text tag as HTML (useful for a multi-line line, where @: is good for a single line).

+6
source

All Articles