ASP.NET MVC Razor

MVC项目中多个页面有相同的东西,框架中提供了几种解决方案: partialView,Layout,section

一、partialView分布页

1用户控件axcs——partial:重复的小模块

cshtml 页面代码
@{
    ViewBag.Title = "PartialPage";
    Layout = null;
}

<h3>这里是一个重复展示的小模块儿 @Model</h3>
Partial页面代码
       [ChildActionOnly]//不能被单独请求
        public ActionResult Render()
        {
            this.ViewBag.Name = "Jacob";
            return View();
            //return PartialView()  //指定分部视图,在_ViewStatrt.cshtml中指定的Layout会无效
        }
Action Render方法代码
@{
    ViewBag.Title = "Render";
    Layout = null;
}

<h2>Render  @ViewBag.Name</h2>
Action Render页面代码

执行页面效果如图:

二、Layout布局页

master——Layout布局页

MVC项目中如果不写布局页,默认布局页为 Layout = "~/View/Shared/_Layout.cshtml";

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - 我的 ASP.NET 应用程序</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                </button>
                @Html.ActionLink("应用程序名称", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
        </div>
    </div>
    <div class="container body-content">
        <p>
            ***********************华丽的头部分隔线******************************
        </p>
        @RenderBody()
        <hr />
        <footer>
            <p>***********************华丽的底部分隔线******************************</p>
            <p>&copy; @DateTime.Now.Year - 我的 ASP.NET 应用程序</p>
            
        </footer>
    </div>
</body>
</html>
自定义布局页代码

效果如下图:

三、Section

 在具体的业务页面 写section节点代码

section节点代码

在布局页里写有
@RenderSection(SectionName, required: false)
最终生成的页面里会将cshtml 对应Section节点 替换到layout页面代码上
required:true表示页面必须有该节点,false表示可以有可以没有

猜你喜欢

转载自www.cnblogs.com/Dewumu/p/10458805.html