[Go to site: main page, start]

0% found this document useful (0 votes)
24 views10 pages

Razor Syntax Cheat Sheet for ASP.NET

Razor Syntax allows embedding C# code into ASP.NET views using keywords like @. This allows dynamically generating HTML at runtime. The @page directive indicates a file is a Razor Page. The @model directive specifies the data model available to the view. Razor uses @ to transition between HTML and C#, and conditionals, loops, and other C# elements use syntax similar to regular C# with the addition of the @ symbol in some places.

Uploaded by

cf8qrn9q4r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views10 pages

Razor Syntax Cheat Sheet for ASP.NET

Razor Syntax allows embedding C# code into ASP.NET views using keywords like @. This allows dynamically generating HTML at runtime. The @page directive indicates a file is a Razor Page. The @model directive specifies the data model available to the view. Razor uses @ to transition between HTML and C#, and conditionals, loops, and other C# elements use syntax similar to regular C# with the addition of the @ symbol in some places.

Uploaded by

cf8qrn9q4r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

19/01/2024, 13:08 Learn [Link]: ASP.

NET: Razor Syntax Cheatsheet | Codecademy


Cheatsheets / Learn [Link]

[Link]: Razor Syntax

Razor Syntax

Razor Syntax allows you to embed code (C#) into page @page
views through the use of a few keywords (such as “@”),
and then have the C# code be processed and
@model IndexModel
converted at runtime to HTML. In other words, rather <h2>Welcome</h2>
than coding static HTML syntax in the page view, a user
can code in the view in C# and have the Razor engine
convert the C# code into HTML at runtime, creating a
<ul>
dynamically generated HTML web page. @for (int i = 0; i < 3; i++)
{
<li>@i</li>
}
</ul>

The @page Directive

In a Razor view page (.cshtml), the @page directive @page


indicates that the file is a Razor Page.
@model IndexModel
In order for the page to be treated as a Razor Page, and
have [Link] parse the view syntax with the Razor
engine, the directive @page should be added at the <h1>Welcome to my Razor Page</h1>
top of the file.
<p>Title: @[Link]</p>
There can be empty space before the @page
directive, but there cannot be any other characters,
even an empty code block.

[Link] 1/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

The @model Directive

The page model class, i.e. the data and methods that @page
hold the functionality associated with a view page, is
@model PersonModel
made available to the view page via the @model
directive.
By specifying the model in the view page, Razor exposes // Rendering the value of FirstName in
a Model property for accessing the model passed to
PersonModel
the view page. We can then access properties and
functions from that model by using the keyword <p>@[Link]</p>
Model or render its property values on the browser
by prefixing the property names with @Model , e.g. <ul>
@[Link] .
// Accessing the value of FavoriteFoods
in PersonModel
@foreach (var food in
[Link])
{
<li>@food</li>
}
</ul>

Razor Markup

Razor pages use the @ symbol to transition from HTML @page


to C#. C# expressions are evaluated and then rendered
@model PersonModel
in the HTML output. You can use Razor syntax under the
following conditions:
1. Anything immediately following the @ is // Using the `@` symbol:
assumed to be C# code.
<h1>My name is @[Link] and I am
2. Code blocks must appear within @{ ... }
brackets.
@[Link] years old </h1>
3. A single line of code that uses spaces should be
surrounded by parentheses, ( ) . // Using a code block:
@{
var greet = "Hey threre!";
var name = "John";
<h1>@greet I'm @name!</h1>
}

// Using parentheses:
<p>Last week this time: @([Link] -
[Link](7))</p>

[Link] 2/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor Conditionals

Conditionals in Razor code can be written pretty much // if-else if-else statment:
the same way you would in regular C# code. The only
@{ var time = 9; }
exception is to prefix the keyword if with the @
symbol. Afterward, any else or else if
conditions doesn’t need to be preprended with the @ @if (time < 10)
symbol. {
<p>Good morning, the time is: @time</p>
}
else if (time < 20)
{
<p>Good day, the time is: @time</p>
}
else
{
<p>Good evening, the time is: @time</p>
}

Razor Switch Statements

In Razor Pages, a switch statement begins with the @ @{ string day = "Monday"; }
symbol followed by the keyword switch . The
@switch (day)
condition is then written in parentheses and finally the
{
switch cases are written within curly brackets, {} .
case "Saturday":
<p>Today is Saturday</p>
break;
case "Sunday":
<p>Today is Sunday</p>
break;
default:
<p>Today is @day... Looking forward
to the weekend</p>
break;
}

[Link] 3/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor For Loops

In Razor Pages, a for loop is prepended by the @ @{


symbol followed by a set of conditions wrapped in
List<string> avengers = new
parentheses. The @ symbol must be used when
referring to C# code. List<string>()
{
"Spiderman",
"Iron Man",
"Hulk",
"Thor",
};
}

<h1>The Avengers Are:</h1>

@for (int i = 0; i < @[Link];


i++)
{
<p>@avengers[i]</p>
}

[Link] 4/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor Foreach Loops

In Razor Pages, a foreach loop is prepended by the @{


@ symbol followed by a set of conditions wrapped in
List<string> avengers = new
parentheses. Within the conditions, we can create a
variable that will be used when rendering its value on List<string>()
the browser. {
"Spiderman",
"Iron Man",
"Hulk",
"Thor",
};
}

<h1>The Avengers Are:</h1>

@foreach (var avenger in avengers)


{
<p>@avenger</p>
}

Razor While Loops

A while loop repeats the execution of a sequence @{ int i = 0; }


of statements as long as a set of conditions is true ,
once the condition becomes false we break out of
the loop.
@while (i < 5)
When writing a while loop, we must prepend the {
keyword while with the @ symbol and write the <p>@i</p>
condition within parentheses.
i++;
}

[Link] 5/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor View Data

In Razor Pages, you can use the ViewData property // Page Model: [Link]
to pass data from a Page Model to its corresponding
public class IndexModel : PageModel
view page, as well as share it with the layout, and any
partial views. {
ViewData is a dictionary that can contain key- public void OnGet()
value pairs where each key must be a string. The values
{
can be accessed in the view page using the @ symbol.
ViewData["Message"] = "Welcome to my
A huge benefit of using ViewData comes when
working with layout pages. We can easily pass page!";
information from each individual view page such as the ViewData["Date"] = [Link]();
title , into the layout by storing it in the
}
ViewData dictionary in a view page:
}
@{ ViewData["Title"] = "Homepage"
}
We can then access it in the layout like so: // View Page: [Link]
ViewData["Title"] . This way, we don’t need @page
to hardcode certain information on each individual
@model IndexModel
view page.

<h1>@ViewData["Message"]</h1>
<h2>Today is: @ViewData["Date"]</h2>

[Link] 6/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor Shared Layouts

In Razor Pages, you can reduce code duplication by // Layout: _LayoutExample.cshtml


sharing layouts between view pages. A default layout is
<body>
set up for your application in the _Layout.cshtml file
located in Pages/Shared/. ...
Inside the _Layout.cshtml file there is a method call: <div class="container body-content">
RenderBody() . This method specifies the point
@RenderBody()
at which the content from the view page is rendered
relative to the layout defined. <footer>
If you want your view page to use a specific Layout page <p>@[Link] - My [Link]
you can define it at the top by specifying the filename
Application</p>
without the file extension: @{ Layout =
"LayoutPage" } </footer>
</div>
</body>

// View Page: [Link]


@page
@model ExampleModel

@{ Layout = "_LayoutExample" }

<h1>This content will appear where


@RenderBody is called!</h1>

[Link] 7/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor Tag Helpers

In Razor Pages, Tag Helpers change and enhance // Page Model: [Link]
existing HTML elements by adding specific attributes to
public class ExampleModel : PageModel
them. The elements they target are based on the
element name, the attribute name, or the parent tag. {
[Link] provides us with numerous built-in Tag Helpers public string Language { get; set; }
that can be used for common tasks - such as creating
forms, links, loading assets, and more.
public List<SelectListItem> Languages {
get; } = new List<SelectListItem>
{
new SelectListItem { Value = "C#",
Text = "C#" },
new SelectListItem { Value =
"Javascript", Text = "Javascript" },
new SelectListItem { Value = "Ruby",
Text = "Ruby" },
};
}

// View Page: [Link]


<h1>Select your favorite language!</h1>
<form method="post">
// asp-for: The name of the specified
model property.
// asp-items: A collection of
SelectListItemoptions that appear in the
select list.
<select asp-for="Language" asp-
items="[Link]"></select>
<br />
<button type="submit">Register</button>
</form>

// HTML Rendered:
<form method="post">
<select id="Language" name="Language">
<option value="C#">C#</option>
<option
value="Javascript">Javascript</option>
<option value="Ruby">Ruby</option>

[Link] 8/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy
<br>
</select>
<button type="submit">Register</button>
</form>

Razor View Start File

When creating a template with [Link], a // [Link]


[Link] file is automatically generated under
@{
the /Pages folder.
The [Link] file is generally used to define Layout: "_Layout"
the layout for the website but can be used to define }
common view code that you want to execute at the
start of each View’s rendering. The generated file
contains code to set up the main layout for the
application.

Razor Partials

Partial views are an effective way of breaking up large // _MyPartial.cshtml


views into smaller components and reduce complexity.
<form method="post">
A partial consists of fragments of HTML and server-side
code to be included in any number of pages or layouts. <input type="email"
We can use the Partial Tag Helper, <partial> , in name="emailaddress">
order to render a partial’s content in a view page.
<input type="submit">
</form>

// [Link]
<h1> Welcome to my page! </h1>
<h2> Fill out the form below to
subscribe!:</h2>
<partial name="_MyPartial" />

[Link] 9/10
19/01/2024, 13:08 Learn [Link]: [Link]: Razor Syntax Cheatsheet | Codecademy

Razor View Imports

The _ViewImports.cshtml file is automatically // _ViewImports.cshtml


generated under /Pages when we create a template
with [Link].
@using YourProject
Just like the _ViewStart.cshtml file, @namespace [Link]
_ViewImports.cshtml is invoked for all your view pages @addTagHelper *,
before they are rendered.
[Link]
The purpose of the file is to write common directives
that our view pages need. [Link] currently supports a
few directives that can be added such as:
@namespace , @using , @addTagHelpers ,
and @inject amongst a few other ones. Instead of
having to add them individually to each page, we can
place the directives here and they’ll be available
globally throughout the application.

Print Share

[Link] 10/10

Common questions

Powered by AI

Razor Pages employs a code-first approach for loops, involving prepending loop structures with '@' before employing conditions, as opposed to separating server-side and client-side logic as seen in traditional scripting languages. This allows loops such as '@for', '@foreach', and '@while' to be integrated seamlessly with HTML, combining C# logic directly with the page's visual content. The code-first nature ensures logic is processed server-side before rendering as HTML, offering optimized rendering and a unified approach to coding that leverages C#'s robust features directly in the page view .

Razor control structures like conditionals and loops offer functionality akin to standard C# while being optimized for web development. Razor-like C# uses syntax such as '@if', '@foreach', and '@switch' to embed logic directly in HTML. Conditionals let you dynamically adjust HTML content, for example, '@if' is used to conditionally render different HTML content, similar to a standard C# if-statement. Similarly, '@for' and '@foreach' enable looping through collections to render multiple elements dynamically, akin to their C# equivalents. This integration allows seamless execution of logic and rendering of web pages .

The '@page' directive is crucial in Razor Pages as it designates a file as a Razor Page. It is typically positioned at the top of the file to ensure that ASP.NET's Razor engine processes the view syntax correctly. This directive is necessary for the page to be treated as a Razor Page, enabling it to handle routing and HTTP request processing in a way that's integrated with the ASP.NET Core MVC framework .

Partial views in Razor Pages allow complex web applications to be divided into manageable components by reusing HTML and server-side logic across multiple pages. Each partial view is an encapsulated segment containing both markup and logic, invoked using the '<partial>' tag. This modular approach aids in reducing code duplication, enhancing maintainability, and simplifying testing by isolating smaller sections of code independently from the main views, fostering a DRY (Don't Repeat Yourself) principle in application development .

Razor Tag Helpers offer a modern way to work with HTML, enhancing existing HTML elements with server-side capabilities by specifying attributes. Unlike traditional HTML where server-side processing is limited and separate from the markup, Tag Helpers integrate server-side logic directly in the markup, making the code more readable and maintainable. They outperform Web Forms by eliminating special syntax like Web Forms tags, allowing developers to use standard HTML enriched with server-coded intelligence, thus simplifying the development process and enhancing productivity .

Razor syntax allows the embedding of C# code into HTML page views using the '@' character. This code is processed and converted at runtime to HTML by the Razor engine, which enables the creation of dynamic web pages. For instance, in a Razor page (.cshtml), C# expressions can be embedded directly using expressions like '@Model.PropertyName' or within code blocks delineated by '@{ ... }'. This allows developers to build web pages that can change dynamically based on server-side logic .

In Razor Pages, layout pages serve as templates for other pages in the application, defining a common structure for headers, footers, and any recurring content. The layout is specified in the '_Layout.cshtml' file and pages refer to this layout using the '@{ Layout = "_Layout" }' directive. This structure promotes code reuse and maintainability by enabling updates to be made in the layout file, which automatically propagate to all pages using that layout, reducing duplication and synchronizing the design across the application .

The '_ViewImports.cshtml' file in ASP.NET Razor Pages centralizes common directives such as '@namespace', '@using', and '@addTagHelpers'. This file, automatically executed before rendering each view, ensures that specified namespaces and tag helpers are uniformly applied to all pages, promoting code consistency and reducing the need for repetitive declarations in individual view files. This enhances maintainability and streamlines the development process across the application .

ViewData enhances Razor pages by allowing data to be passed from a controller or page model to the view, as well as shared among layouts and partial views. It is a dictionary containing key-value pairs, with keys as strings, enabling the dynamic passing of data such as page titles or messages without hardcoding them into view pages. This flexibility supports scalability and maintainability of ASP.NET applications by centralizing and simplifying data management across views and layouts .

The 'ViewStart.cshtml' file in Razor Pages is responsible for defining common settings, such as the layout page for the application, across all views. This file is executed at the start of each view's rendering process, allowing these settings to be applied globally, reducing repetitive configuration code in individual views and ensuring consistent layout usage throughout the application .

You might also like