Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jetstreamin/6b1cad68c0a17b90594ad1138558997c to your computer and use it in GitHub Desktop.
Save jetstreamin/6b1cad68c0a17b90594ad1138558997c to your computer and use it in GitHub Desktop.
ASP.NET Razor Syntax Reference

ASP.NET Razor Syntax Reference

Code Block

@{
    int x = 123;
    string y = "because.";
}

Expression (Html Encoded)

<span>@model.Message</span>

Expression (Unencoded)

<span>
    @Html.Raw(model.Message)
</span>

Combining Text and markup

@foreach(var item in items) {
    <span>@item.Prop</span>
}

Mixing code and Plain text

@if (foo) {
    <text>Plain Text</text>
}

Mixing code and plain text (alternate)

@if (foo) {
    @:Plain Text is @bar
}

Email Addresses

Hi [email protected]

Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter.

Explicit Expression

<span>ISBN@(isbnNumber)</span>

In this case, we need to be explicit about the expression by using parentheses.

Escaping the @ sign

<span>
    In Razor, you use the
    @@foo to display the value
    of foo
</span>

@@ renders a single @ in the response.

Server side Comment

@*
    This is a server side
    multiline comment
*@

Calling generic method

@(MyClass.MyMethod<AType>())

Use parentheses to be explicit about what the expression is.

Creating a Razor Delegate

@{
    Func<dynamic, object> b =
    @<strong>@item</strong>;
}
@b("Bold this")

Generates a Func<T, HelperResult> that you can call from within Razor. See [this post](http://haacked.com/archive/2011/02/27/templated-razor- delegates.aspx) for more details.

Mixing expressions and text

Hello @title. @name.

NEW IN RAZOR v2.0/ASP.NET MVC 4

Conditional attributes

<div class="@className"></div>

When className = null

<div></div>

When className = ""

<div class=""></div>

When className = "my-class"

<div class="my-class"></div>

Conditional attributes with other literal values

<div class="@className foo bar"></div>

When className = null

<div class="foo bar"></div>

Notice the leading space in front of foo is removed.

When className = my-class

<div class="my-class foo bar"></div>

Conditional Data Attributes

data-* attributes are always rendered.

<div data-x="@xpos"></div>

When xpos = null or ""

<div data-x=""></div>

When xpos = "42"

<div data-x="42"></div>

Boolean attributes

<input type="checkbox checked="@isChecked" />

Examples

When isChecked = true

<input type="checkbox" checked="checked" />

When isChecked = false

<input type="checkbox" />

URL Resolution with tilde

<script src="~/myscript.js"></script>

Examples

When the app is at /

<script src="/myscript.js"></script>

When running in a virtual application named MyApp

<script src="/MyApp/myscript.js"></script>

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment