AspNet MVC4 教学-9:Asp.Net MVC4 利用Layout的几种方法的快速Demo

@{
    ViewBag.Title = "Index5";
    Layout = "~/Views/Home/_MyLayout2.cshtml";
}

<h2>我是Index5</h2>

HomeController.cs文件内容:

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

namespace MvcLayoutTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Index2()
        {
            return View();
        }
        public ActionResult Index3()
        {
            return View();
        }
        public ActionResult Index4()
        {
            return View();
        }
        public ActionResult Index5()
        {
            return View("Index5", "_MyLayout1");
        }
        
    }
}

在Shared下面,新建一个Layout文件:_MyLayout1.cshtml:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <h2>我来自自定义Layout1</h2>
    <div>
        @RenderBody()
    </div>
</body>
</html>

在Home文件夹下新建Layout文件:_MyLayout2.cshtml:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
<h2>我来自自定义Layout2</h2>
    <div>
        @RenderBody()
    </div>
</body>
</html>


Index.cshtml:

@{
    ViewBag.Title = "Index";
}

<h2>我是Index</h2>
@Html.ActionLink("Index2","Index2")
@Html.ActionLink("Index3","Index3")
@Html.ActionLink("Index4","Index4")

Index2.cshtml:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>不使用Layout,我是Index2</title>
</head>
<body>
    <h2>不使用Layout,我是Index2</h2>
</body>
</html>
Index3.cshtml:

@{
    Layout = "~/Views/Shared/_MyLayout1.cshtml";
}
<h2>我是Index3</h2>

Index4.cshtml:

@{
    ViewBag.Title = "Index4";
    Layout = "~/Views/Home/_MyLayout2.cshtml";
}

<h2>我是Index4</h2>

Index5.cshtml:

@{
    ViewBag.Title = "Index5";
    Layout = "~/Views/Home/_MyLayout2.cshtml";
}

<h2>我是Index5</h2>
小结:Layout布局,既可以使用,也可以不使用。既可以在View前面的服务端代码区中声明选用那种布局,也可以采用Action中进行动态分配布局。如果两种方法都使用,Action中声明的优先。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gCodeTop 格码拓普 老师

您的鼓励.我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值