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!
Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.
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.
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 ).
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.
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>
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With