Razor Cheat Sheet
Razor Cheat Sheet
uk
Index
Razor Comments
Inline expression
Multi-statement block
Store String
Store Date
Store Date
Variables
Convert Data Types
Loops
Arrays
Conditionals
Using
Models View
Dependency Injection
Add Functions
Create Templates
Conditional Attributes
Forms
Add Partials
Add link to a page
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
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
@{
@* This is a comment. *@
var theVar = 17;
}
back to top
1
jasonwilliams@letuscode.co.uk
Inline expression
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p> }
back to top
Store String
/* A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quota
Store Date
back to top
@{
var totalMessage = "";
if(IsPost)
{
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
back to top
Variables
@{
// Assigning a string to a variable.
var greeting = "Welcome!";
Display Variables
@{
// Embedding the value of a variable into HTML markup.
<p>@greeting, friends!</p>
back to top
AsInt(), if (myString.IsInt())
Converts a string to an integer.
IsInt() {myInt=myString.AsInt();
if (myString.IsFloat())
AsFloat(), IsFloat() Converts a string to a floating-point number.
{myFloat=myString.AsFloat();}
if (myString.IsDecimal())
AsDecimal(), IsDecimal() Converts a string to a decimal number..
{myDec=myString.AsDecimal();}
myString="10/10/2012";
AsDateTime(), IsDateTime() Converts a string to an ASP.NET DateTime type.
myDate=myString.AsDateTime();
AsBool(), myString="True";
Converts a string to a Boolean..
IsBool() myBool=myString.AsBool();
myInt=1234;
ToString() Converts any data type to a string.
myString=myInt.ToString();
@{
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
Loops
Standard Loop
ForEach Loops
<ul>
@foreach (var myItem in Request.ServerVariables)
{
<li>@myItem</li>
}
</ul> 3
jasonwilliams@letuscode.co.uk
While Loops
@{
var countNum = 0;
while (countNum < 50)
{
countNum += 1;
<p>Line #@countNum: </p>
}
}
back to top
Arrays
@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai")+1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
back to top
Conditionals
If
@{
var showToday = true;
if(showToday)
{
@DateTime.Today;
}
}
If Else
@{
var showToday = false;
if(showToday)
{
@DateTime.Today;
}
else
{
<text>Sorry!</text>
}
}
Else If
@{
var theBalance = 4.99;
if(theBalance == 0)
{
<p>You have a zero balance.</p>
}
else if (theBalance > 0 && theBalance <= 5)
{
<p>Your balance of $@theBalance is very low.</p>
}
else
{
4
jasonwilliams@letuscode.co.uk
<p>Your balance is: $@theBalance</p>
}
}
Switch Statement
@{
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;
}
@try
{
throw new InvalidOperationException("You did something invalid.");
}
catch (Exception ex)
{
<p>The exception message: @ex.Message</p>
}
finally
{
<p>The finally statement.</p>
}
back to top
Using
/* The @using directive adds the C# using directive to the generated view:*/
@using System.IO
@{
var dir = Directory.GetCurrentDirectory();
}
<p>@dir</p>
back to top
Models View
// The @model directive specifies the type of the model passed to a view:
@model TypeNameOfModel
Access Model
Dependency Injection
@inject +ServiceName
back to top
5
jasonwilliams@letuscode.co.uk
Add Functions
@functions {
public string GetHello()
{
return "Hello";
}
}
back to top
Create Templates
Create a class
@{
Func<dynamic, object> petTemplate = @<p>You have a pet named @item.Name.</p>;
<!-- The template is rendered with pets supplied by a foreach statement: -->
Rendered output
back to top
Conditional Attributes
@{
string divStyle = null;
if(Request.QueryString["style"] != null)
{
divStyle = "background-color: yellow;";
}
}
<div style="@divStyle">Hello, world!</div>
back to top
Forms
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Movie.Title" class="control-label"></label>
<input asp-for="Movie.Title" class="form-control" />
<span asp-validation-for="Movie.Title" class="text-danger"></span>
</div>
<div class="form-group">
6
jasonwilliams@letuscode.co.uk
<label asp-for="Movie.ReleaseDate" class="control-label"></label>
<input asp-for="Movie.ReleaseDate" class="form-control" />
<span asp-validation-for="Movie.ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
back to top
Add Partials
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
back to top
<div>
<a asp-page="./Index">Back to List</a>
</div>
back to top
<tbody>
@foreach (var item in Model.Movie)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.ID">Details</a> |
<a asp-page="./Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
back to top