Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor syntax to render section based on condition

Tags:

I got a view with Layout defined. In the layout, there is a section:

@RenderSection("JavaScript", required: false)

In the view, based on a condition, I want to either render certain JavaScript to the section or not.

@if (condition) {      @section JavaScript     {         <script type="text/javascript>            $(document).ready(function(){              //bla...            });         </script>     } } 

The above syntax is wrong. What's the correct syntax?

Edit

Basically, I got a partial view which needs to be rendered based on a condition. If the condition is true, then I need to render the partial view together with some JavaScript for the partial view, which I want to go to the "JavaScript" section. How can I do that?

like image 244
Dimskiy Avatar asked May 12 '11 18:05

Dimskiy


People also ask

How do you write if condition in Razor view?

The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.

What is Razor syntax in C#?

Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output. When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup.

What is Razor in MVC What are the main Razor syntax rules?

Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.

What is RenderSection in Razor?

RenderSection(String) In layout pages, renders the content of the section named name . RenderSection(String, Boolean) In layout pages, renders the content of the section named name .


1 Answers

@section blocks can only appear in markup contexts.

You can write

@if (condition) {      <text>         @section JavaScript         {             <script type="text/javascript>                $(document).ready(function(){                  //bla...                });             </script>         }     </text> } 
like image 155
SLaks Avatar answered Oct 06 '22 14:10

SLaks