本实验演示基本的 Razor 语法。

    代码很简单,运行起来看看效果就能懂。

    Model 类:

    1. namespace MyWebApp.Models
    2. {
    3. public class Product
    4. {
    5. public int ID { get; set; }
    6. public string Name { get; set; }
    7. public double Price { get; set; }
    8. }
    9. public class Discount
    10. {
    11. public DateTime Start { get; set; }
    12. public DateTime End { get; set; }
    13. public double Rate { get; set; }
    14. }
    15. public class ProductListVM
    16. {
    17. public Discount Discount { get; set; }
    18. public IList<Product> Products { get; set; }
    19. }
    20. }

    Product 和 Discount 是领域模型,ProductListVM 是 View Model。

    ProductList.cshtml:

    1. @using MyWebApp.Models
    2. @model ProductListVM
    3. @{
    4. var start = this.Model.Discount.Start.ToString("d");
    5. var end = this.Model.Discount.End.ToString("d");
    6. var rate = this.Model.Discount.Rate;
    7. var off = (1 - rate) * 100;
    8. }
    9. <html>
    10. <body>
    11. <h1>Product List</h1>
    12. <h4 style="color: blue">The @off% off discount will be valid from @start to @end!</h4>
    13. <table border="1">
    14. <tr>
    15. <th>ID</th><th>Name</th><th>Price</th><th>Discount Price</th>
    16. </tr>
    17. @foreach (var p in this.Model.Products)
    18. {
    19. <tr>
    20. <td>@p.ID</td><td>@p.Name</td><td>@p.Price</td><td>@(p.Price * rate)</td>
    21. </tr>
    22. }
    23. </table>
    24. </body>
    25. </html>

    Controller:

    1. namespace MyWebApp.Controllers
    2. {
    3. public class ProductController : Controller
    4. {
    5. public IActionResult Index()
    6. {
    7. var vm = new ProductListVM();
    8. vm.Discount = new Discount { Start = DateTime.Today, End = DateTime.Today.AddDays(30), Rate = 0.75 };
    9. vm.Products = new List<Product>();
    10. vm.Products.Add(new Product { ID = 101, Name = "Book", Price = 20 });
    11. vm.Products.Add(new Product { ID = 102, Name = "Bike", Price = 30 });
    12. vm.Products.Add(new Product { ID = 103, Name = "Fireworks", Price = 40 });
    13. return View("ProductList", vm);
    14. }
    15. ...
    16. }
    17. }

    运行效果:
    4.5.1 Lab 1 Razor 语法基础 - 图1