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

422101-20170531184444071-77036231.png

页面增加逻辑

@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
}

本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6925466.html,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值