I'd like to execute a piece of JavaScript when a certain condition is true in my view model:
<script type="text/javascript"> @if (Model.Employees.Count > 1) { executeJsfunction(); } </script>
This code doesn't compile, how should I do this?
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.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
If you want to write a function, you can't just open new @{ } razor block and write it there… it won't work. Instead, you should specify @functions { } so that inside the brackets you will write your own C#/VB.NET functions/methods. This code will print the numbers from 1 to 10: Number 1.
Try with this:
<script type="text/javascript"> @if (Model.Employees.Count > 1) { @:executeJsfunction(); } </script>
Note the "@:"
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