版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xc917563264/article/details/82977233
Razor视图引擎会编译应用程序中的视图,以改善性能。视图会被编译为C#的类,然后被编译。这就是视图能够如此方便地包含C#代码的原因。
在访问视图时,MVC会依照当前文件夹下,Shared文件夹按顺序访问。
视图的全部目的,是让开发人员将域模型部分的内容渲染成用户界面。为了达到这一目的,需要对视图添加动态内容。动态内容是运行时生成的,并且随着每个请求而不同。
技术 |
何时使用 |
内联代码 |
在HTML代码中插入逻辑片段,如if,for等 |
HTML辅助器代码 |
用于生成一个独立的HTML元素 |
分段 |
用于创建内容分段,这种分段用于布局的特定位置 |
分部视图 |
在多个不同的地方,使用同样的Razor标签和HTML标记 |
子动作 |
当你希望控制器的某个逻辑用于应用程序的多个地方时 |
分段的Demo,GetSection.cshtml:
@model string[]
@{
ViewBag.Title = "GetSection";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Header{
<div>
@foreach(var item in new string[] { "Home", "List", "Item" })
{
<a href="javascript:void(0)">@item</a>
}
</div>
}
@section Body{
<div>
This is a list of fruits names:
@foreach (var item in Model)
{
<span><b>@item</b></span>
}
</div>
}
@section Footer{
<div>
This is Footer
</div>
}
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div>
这是分段视图:
</div>
@RenderSection("Header")
<div>
这是分段视图:
</div>
@RenderSection("Body")
<div>
这是分段视图:
</div>
@RenderSection("Footer")
<div>
使用可选分段,这样即使不存在这个分段,系统也不会报错哦
</div>
@RenderSection("Footer2",false)
</body>
</html>
分部视图的Demo,GetParial.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetParital</title>
</head>
<body>
<div>
This is GetPartial
</div>
<div>
@Html.Partial("MyPartial")
</div>
</body>
</html>
MyParital.cshtml:
<div>
this is the message from the partial view
<a href="GetSection">GetSection</a>
</div>
子动作的Demo,HomeController.cs:
/// <summary>
/// 调用子动作
/// </summary>
/// <returns></returns>
public ActionResult GetChildAction()
{
return View();
}
[ChildActionOnly]
public ActionResult Time()
{
return PartialView(DateTime.Now);
}
GetChildAction.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetStrongResult</title>
</head>
<body>
<div>
This is GetChildAction
</div>
<div>
@Html.Action("Time")
</div>
</body>
</html>
Time.cshtml:
@model DateTime?
<p>the time is @Model.ToShortTimeString()</p>