https://github.com/jwill9999/asp.net-razor-cheatsheet
ASP.NET Razor Cheatsheet
https://github.com/jwill9999/asp.net-razor-cheatsheet
asp-net asp-net-core asp-net-core-mvc aspnet-core razor-pages
Last synced: 11 months ago
JSON representation
ASP.NET Razor Cheatsheet
- Host: GitHub
- URL: https://github.com/jwill9999/asp.net-razor-cheatsheet
- Owner: jwill9999
- Created: 2018-12-04T13:33:23.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-12-04T13:34:24.000Z (over 7 years ago)
- Last Synced: 2025-05-06T20:35:58.160Z (about 1 year ago)
- Topics: asp-net, asp-net-core, asp-net-core-mvc, aspnet-core, razor-pages
- Size: 4.88 KB
- Stars: 2
- Watchers: 0
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ASP.NET Razor - C# Code Syntax - [PDF Download Cheatsheet](https://1drv.ms/b/s!Ai0GNI50Q5GAgdQ0B2b3gDPlXcxM_w)
# Index
[Razor Comments](#Razor-Comments)
[Inline expression](#Inline-expression)
[Multi-statement block](#Multi-statement-block)
[Store String](#Store-Date)
[Store Date](#Tag-Helpers)
[Store Date](#Tag-Helpers)
[Variables](#Variables)
[Convert Data Types ](#Convert-Data-Types )
[Loops](#Loops)
[Arrays](#Arrays)
[Conditionals](#Conditionals)
[Using](#Using)
[Models View](#Models-View)
[Dependency Injection](#Dependency-Injection)
[Add Functions](#Add-Functions)
[Create Templates ](#Create-Templates )
[Conditional Attributes](#Conditional-Attributes)
[Forms](#Forms)
[Add Partials](#Add-Partials)
[Add link to a page](#Add-link-to-a-page)
[ Loop through a list and output](#Loop-through-a-list-and-output)
### Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages
## Razor Comments
```c#
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
```
```c#
@{
@* This is a comment. *@
var theVar = 17;
}
```
[back to top](#Index)
## Single statement block
```c#
@{ var myMessage = "Hello World"; }
```
## Inline expression
```c#
@{ var myMessage = "Hello World"; }
```
## Multi statement block
```c#
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
The greeting is: @greetingMessage
}
```
[back to top](#Index)
## Store String
```c#
/* A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:*/
@{ var welcomeMessage = "Welcome, new members!"; }
@welcomeMessage
```
## Store Date
```c#
@{ var year = DateTime.Now.Year; }
```
[back to top](#Index)
## Read User Input
```c#
@{
var totalMessage = "";
if(IsPost)
{
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
```
[back to top](#Index)
## Variables
```c#
@{
// Assigning a string to a variable.
var greeting = "Welcome!";
// Assigning a number to a variable.
var theCount = 3;
// Assigning an expression to a variable.
var monthlyTotal = theCount + 5;
// Assigning a date value to a variable.
var today = DateTime.Today;
// Assigning the current page's URL to a variable.
var myPath = this.Request.Url;
// Declaring variables using explicit data types.
string name = "Joe";
int count = 5;
DateTime tomorrow = DateTime.Now.AddDays(1);
}
```
### Display Variables
```c#
@{
// Embedding the value of a variable into HTML markup.
@greeting, friends!
// Using variables as part of an inline expression.
The predicted annual total is: @( monthlyTotal * 12)
// Displaying the page URL with a variable.
The URL to this page is: @myPath
}
```
[back to top](#Index)
## Convert Data Types
| Method | Description |Examples |
| ------------- |:-------------:| -----:|
|AsInt(),
IsInt() | Converts a string to an integer. | ``` if (myString.IsInt())```
```{myInt=myString.AsInt();```|
|AsFloat(), IsFloat()| Converts a string to a floating-point number.|```if (myString.IsFloat())```
```{myFloat=myString.AsFloat();}```|
|AsDecimal(), IsDecimal()| Converts a string to a decimal number..|```if (myString.IsDecimal())```
```{myDec=myString.AsDecimal();}```|
|AsDateTime(), IsDateTime()|Converts a string to an ASP.NET DateTime type.| ```myString="10/10/2012";```
``` myDate=myString.AsDateTime();```|
|AsBool(),
IsBool()|Converts a string to a Boolean..| ```myString="True";```
```myBool=myString.AsBool();```|
|ToString()|Converts any data type to a string.| ```myInt=1234;```
```myString=myInt.ToString();```|
### Coverting Data Types example
```c#
@{
var total = 0;
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
}
}
```
[back to top](#Index)
# Loops
## Standard Loop
```c#
@for (var i = 0; i < people.Length; i++)
{
var person = people[i];
Name: @person.Name
}
```
## ForEach Loops
```c#
- @myItem
@foreach (var myItem in Request.ServerVariables)
{
}
```
## While Loops
```c#
@{
var countNum = 0;
while (countNum < 50)
{
countNum += 1;
Line #@countNum:
}
}
```
[back to top](#Index)
## Arrays
```c#
@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai")+1;
int len = members.Length;
string x = members[2-1];
}
Members
@foreach (var person in members)
{
@person
}
The number of names in Members are @len
The person at position 2 is @x
Kai is now in position @i
```
[back to top](#Index)
# Conditionals
## If
```c#
@{
var showToday = true;
if(showToday)
{
@DateTime.Today;
}
}
```
## If Else
```c#
@{
var showToday = false;
if(showToday)
{
@DateTime.Today;
}
else
{
Sorry!
}
}
```
## Else If
```c#
@{
var theBalance = 4.99;
if(theBalance == 0)
{
You have a zero balance.
}
else if (theBalance > 0 && theBalance <= 5)
{
Your balance of $@theBalance is very low.
}
else
{
Your balance is: $@theBalance
}
}
```
## Switch Statement
```c#
@{
var weekday = "Wednesday";
var greeting = "";
switch(weekday)
{
case "Monday":
greeting = "Ok, it's a marvelous Monday";
break;
case "Tuesday":
greeting = "It's a tremendous Tuesday";
break;
case "Wednesday":
greeting = "Wild Wednesday is here!";
break;
default:
greeting = "It's some other day, oh well.";
break;
}
Since it is @weekday, the message for today is: @greeting
}
```
## Try Catch Finally
```c#
@try
{
throw new InvalidOperationException("You did something invalid.");
}
catch (Exception ex)
{
The exception message: @ex.Message
}
finally
{
The finally statement.
}
```
[back to top](#Index)
## Using
```c#
/* The @using directive adds the C# using directive to the generated view:*/
@using System.IO
@{
var dir = Directory.GetCurrentDirectory();
}
@dir
```
[back to top](#Index)
## Models View
```c#
// The @model directive specifies the type of the model passed to a view:
@model TypeNameOfModel
```
## Access Model
```html
```
## Dependency Injection
```c#
@inject +ServiceName
```
[back to top](#Index)
## Add Functions
```html
@functions {
public string GetHello()
{
return "Hello";
}
}
```
[back to top](#Index)
## Create Templates
Create a class
```c#
public class Pet
{
public string Name { get; set; }
}
```
create a .```cshtml``` page
```html
@{
Func petTemplate = @
You have a pet named @item.Name.
; var pets = new List
{
new Pet { Name = "Rin Tin Tin" },
new Pet { Name = "Mr. Bigglesworth" },
new Pet { Name = "K-9" }
};
@foreach (var pet in pets)
{
@petTemplate2(pet)
}
}
```
Rendered output
```html
You have a pet named Rin Tin Tin.
You have a pet named Mr. Bigglesworth.
You have a pet named K-9.
```
[back to top](#Index)
## Conditional Attributes
```html
@{
string divStyle = null;
if(Request.QueryString["style"] != null)
{
divStyle = "background-color: yellow;";
}
}
```
[back to top](#Index)
## Forms
```html
```
[back to top](#Index)
## Add Partials
```js
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
```
[back to top](#Index)
## Add link to a page
```html
```
[back to top](#Index)
## Loop through a list and output
```html
@foreach (var item in Model.Movie)
{
@Html.DisplayFor(modelItem => item.Title)
@Html.DisplayFor(modelItem => item.ReleaseDate)
@Html.DisplayFor(modelItem => item.Genre)
@Html.DisplayFor(modelItem => item.Price)
Edit |
Details |
Delete
}
```
[back to top](#Index)