Razor小案例

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Razor.Models
{
    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 { set; get; }

    }
}

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Razor.Models;

namespace Razor.Controllers
{
    public class HomeController : Controller
    {
        Product myProduct = new Product 
        {
            ProductID = 1,
            Name = "Kayak",
            Description = "A boat for one person",
            Category = "Watersports",
            Price = 275M
        }; // 定义一个全局对象

        public ActionResult Index()
        {
            return View(myProduct);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

View

@model Razor.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @Model.Name
    </div>
</body>
</html>

增加_BasicLayout.cshtml

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <h1>Product Information</h1>
        <div style="padding: 20px; border: solid medium black; font-size: 20pt">
            @RenderBody()
        </div>
        <h2>Visit <a href="http://apress.com">Apress</a></h2>
    </div>
</body>
</html>

修改view

@model Razor.Models.Product

@{
    ViewBag.Title = "Product Name";
    Layout = "~/Views/_BasicLayout.cshtml";
}

@Model.Name

页面增加逻辑

@switch ((int)ViewBag.ProductCount)
{
    case 0:
        @: Out of Stock
    break;
case 1:
        <b>Low Stock (@ViewBag.ProductCount)</b>
        break;
default:
        @ViewBag.ProductCount
        break;
}

@if (ViewBag.ProductCount == 0)
{
    @:Out of Stock                
} else if (ViewBag.ProductCount == 1) {
    <b>Low Stock (@ViewBag.ProductCount)</b>
}
else
{
    @ViewBag.ProductCount
}
posted @ 2017-05-31 18:32  TBHacker  阅读(307)  评论(0编辑  收藏  举报