Razor Vs WebForms - Syntax
Razor Vs WebForms - Syntax
Razor Vs WebForms - Syntax
Razor
Code Block
@{
<%
int x = 123;
int x = 123;
string y = "because.";
string y =
"because.";
%>
Expression (Html
<span>@model.Message</span
<span><%:
Encoded)
>
model.Message
%></span>
<span>
<span><%=
@Html.Raw(model.Message)
model.Message
</span>
%></span>
<% foreach(var
markup
<span>@item.Prop</span>
Expression
(Unencoded)
<span><%:
item.Prop
%></span>
<% } %>
@if (foo) {
<text>Plain Text</text>
Plain Text
<% } %>
@if (foo) {
Same as above
Email Addresses
Hi philha@example.com
Explicit Expression
<span>ISBN@(isbnNumber)</sp
an>
of foo</span>
@*
<%--
multiline comment
multiline comment
*@
--%>
@(MyClass.MyMethod<AType>())
Use parentheses to be
Calling generic
method
@{
Creating a Razor
Delegate
Func<dynamic, object> b =
@<strong>@item</strong>;
}
Generates a Func<T,
HelperResult> that you can
call from within Razor. See
this blog post for more
details.
@b("Bold this")
Mixing expressions
and text
Operators
Operator Description
+
*
/
Examples
@(5 + 13)
@{ var netWorth = 150000; }
@{ var newTotal = netWorth * 2; }
@(newTotal / 2)
var age = 17;
==
!=
<
>
<=
>=
+=
-=
()
[]
int theCount = 0;
theCount += 1; // Adds 1 to count
@(3 + 7)
@Request.MapPath(Request.FilePath);
var income =
Request["AnnualIncome"];
// Continue processing
&&
||
Type Casting
Method
AsInt(),
IsInt()
AsBool(),
IsBool()
AsFloat(),
IsFloat()
Description Example
Converts a
string that
represents a
whole
number (like
"593") to an
integer.
Converts a
string like
"true" or
"false" to a
Boolean
type.
Converts a
string that
has a
decimal
value like
"1.3" or
"7.439" to a
floatingpoint
number.
var myIntNumber = 0;
var myStringNum = "539";
if(myStringNum.IsInt()==true){
myIntNumber = myStringNum.AsInt();
}
AsDecimal(),
IsDecimal()
AsDateTime(),
IsDateTime()
Converts a
string that
has a
decimal
value like
"1.3" or
"7.439" to a
decimal
number. (In
ASP.NET, a
decimal
number is
more precise
than a
floatingpoint
number.)
Converts a
string that
represents a
date and
time value
to the
ASP.NET
DateTime
type.
ToString()
Converts
any other
data type to
a string.
http://www.asp.net/webmatrix/tutorials/2-introduction-to-asp-net-web-programmingusing-the-razor-syntax