1】基本语法@{ int num1 =10;
int num2 =5;
int sum = num1 + num2;
@sum;
@(num1 +num2);
string color ="Red";
<font color="@color">@sum</font>
}
2】特殊语法
输出@符号:@@
输出Email地址:Razor模板会自动识别出Email地址,所以不需要我们进行任何的转换。而在代码块中,只需要使用 @:Tom@gmail.com 即可。@:表示后面的内容为文本。
输出HTML代码(包含标签):直接输出,string html = "<font color='red'>文本</font>"; @html
输出HTML内容(不包含标签):有两种方法,第一种:IHtmlString html=new HtmlString("<font color='red'>文本</font>"); @html; 第二种:string html = "<font color='red'>文本</font>"; @Html.Raw(html);
3】输出列表@foreach (var p in Model) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
4】输出用户控件@foreach (var p in Model.Products) {
Html.RenderPartial("ProductSummary", p);
}
5】在controller中引用用户控件需要传递数据时,可以使用下列方法
public ViewResult Summary(Cart cart) {
return View(cart);
}
输出时: @{Html.RenderAction("Summary", "Cart");}
public PartialViewResult Menu() {
IEnumerable<string> categories = repository.Products
.Select(x => x.Category)
.Distinct()
.OrderBy(x => x);
return PartialView(categories);
}
输出时: @{ Html.RenderAction("Menu", "Nav"); }
int num2 =5;
int sum = num1 + num2;
@sum;
@(num1 +num2);
string color ="Red";
<font color="@color">@sum</font>
}
2】特殊语法
输出@符号:@@
输出Email地址:Razor模板会自动识别出Email地址,所以不需要我们进行任何的转换。而在代码块中,只需要使用 @:Tom@gmail.com 即可。@:表示后面的内容为文本。
输出HTML代码(包含标签):直接输出,string html = "<font color='red'>文本</font>"; @html
输出HTML内容(不包含标签):有两种方法,第一种:IHtmlString html=new HtmlString("<font color='red'>文本</font>"); @html; 第二种:string html = "<font color='red'>文本</font>"; @Html.Raw(html);
3】输出列表@foreach (var p in Model) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
4】输出用户控件@foreach (var p in Model.Products) {
Html.RenderPartial("ProductSummary", p);
}
5】在controller中引用用户控件需要传递数据时,可以使用下列方法
public ViewResult Summary(Cart cart) {
return View(cart);
}
输出时: @{Html.RenderAction("Summary", "Cart");}
public PartialViewResult Menu() {
IEnumerable<string> categories = repository.Products
.Select(x => x.Category)
.Distinct()
.OrderBy(x => x);
return PartialView(categories);
}
输出时: @{ Html.RenderAction("Menu", "Nav"); }