Razor 初见
- Razor就是用来实现在CSHTML业务逻辑的,减少复杂度
- 共用模板 _BasicLayout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<style>
#mainDiv
{
padding:20px;
border:solid medium black;
font-size:20 pt
}
</style>
</head>
<body>
<h1>Product Information</h1>
<div id="mainDiv">
@RenderBody()
</div>
</body>
</html>
@{
Layout = "_BasicLayout";
}
@using Razor.Models
@model Product
@{
ViewBag.Title = "Product Name";
}
<div data-productid="@Model.ProductID" data-stocklevel="@ViewBag.StockLevel">
<p>Product Name:@Model.Name</p>
<p>Product Price:@($"{Model.Price:C2}")</p>
<p>Stock Level:
@*方法一,不喜欢用的*@
@switch ((int)ViewBag.StockLevel)
{
case 0:
@:Out of Stock
break;
case 1:
case 2:
case 3:
<b>Low Stock(@ViewBag.StockLevel)</b>
break;
default:
@:@ViewBag.StockLevel in Stock
break;
}
@*第二种方法我喜欢容易懂*@
@if(ViewBag.StockLevel==0)
{
@:Out of Stock
}
else if(ViewBag.StockLevel>0&&ViewBag.StockLevel<=3)
{
<b>Low Stock(@ViewBag.StockLevel)</b>
}
else
{
@:@ViewBag.StockLevel in Stock
}
</p>
</div>
@model Product[]@*调用model里的Product[]数组数据*@
@{
ViewBag.Title = "Product Name";
}
<table>
<thead>
<tr><th>Name</th><th>Price</th></tr>
</thead>
<tbody>
@foreach(Product p in Model)
{
<tr>
<td>@p.Name</td>
<td>@($"{p.Price:C2}")</td>
</tr>
}
</tbody>
</table>