Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally execute JavaScript in Razor view

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?

like image 828
ngruson Avatar asked Nov 23 '12 20:11

ngruson


People also ask

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.

Is Razor better than MVC?

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.

How do you write a function in Razor view?

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.


1 Answers

Try with this:

<script type="text/javascript">     @if (Model.Employees.Count > 1)     {         @:executeJsfunction();     } </script> 

Note the "@:"

like image 82
thepirat000 Avatar answered Sep 30 '22 08:09

thepirat000