使用Razor

新建一个名称为Rezor的mvc空项目,定义一个模型内容

  public class Product
    {
        //定义模型
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

创建布局  _BasicLayout.cshtml

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title@*ViewBag中查找一个title的属性,目的是设置title元素的内容*@</title>
</head>
<body>
    <h1>Product Information</h1>
    <div style="padding:20px;border:solid medium black;font-size:20pt;">
        @RenderBody()@*RenderBoy方法的调用会将动作方法所指定的视图内容查到布局标记中*@
    </div>
    <h2>Visit <a href="http://apress.com">Apress</a></h2>
</body>
</html>

定义一个DomeArray()方法

  public ActionResult DemoArray()
        {
            Product[] array =
            {
                new Product{Name="Kaysk",Price=275M},
                new Product{Name="Leftjacket",Price=19.50M},
                new Product{Name="Soccer ball",Price=48.95M},
                new Product{Name="Corner flag",Price=34.95M}
            };
            return View(array);
        }

添加DomeArray页面 ,使用@using引入命名空间 Rezor.Models,使用布局_BasicLayout.cshtml

@using Rezor.Models
@model Product[]
@{
    ViewBag.Title = "DemoArray";
    Layout = "~/Views/Shared/_BasicLayout.cshtml";
}

@if (Model.Length > 0)
{
    <table>
        <thead><tr><th>Product</th><th>Price</th></tr></thead>
        <tbody>
            @foreach (Product p in Model)
            {
                <tr>
                    <td>@p.Name</td>
                    <td>$@p.Price</td>
                </tr>
            }
        </tbody>
    </table>
}

运行

原文地址:https://www.cnblogs.com/shapaozi/p/7430134.html