节只在查看工作不局部视图或查看 组件工作(Default.cshtml
独立于主ViewResult
及其Layout
值执行默认情况下是null
),这就是由设计。
你可以用它来render sections
的Layout
的partial view
或view component's
视图声明。但是,在部分和视图组件中定义的部分不会返回到呈现视图或其布局。 如果您想在部分视图或视图组件中使用jQuery或其他库引用,则可以在Layout
页面中将库引入head
而不是body
。
实施例:
查看组件: ViewComponent的
public class ContactViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
位置:
/Views/[CurrentController]/Components/[NameOfComponent]/Default.cshtml
/Views/Shared/Components/[NameOfComponent]/Default.cshtml
Default.cshtml:
@model ViewComponentTest.ViewModels.Contact.ContactViewModel
<form method="post" asp-action="contact" asp-controller="home">
<fieldset>
<legend>Contact</legend>
Email: <input asp-for="Email" /><br />
Name: <input asp-for="Name" /><br />
Message: <textarea asp-for="Message"></textarea><br />
<input type="submit" value="Submit" class="btn btn-default" />
</fieldset>
</form>
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
...
@RenderSection("styles", required: false)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
@RenderBody()
...
//script move to head
@RenderSection("scripts", required: false)
</body>
</html>
查看。CSHTML:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
..................
@{Html.RenderPartial("YourPartialView");}
..................
@await Component.InvokeAsync("Contact")
..................
@section Scripts {
<script>
//Do somthing
</script>
}
View组件由grahamehorner:(可以了解更多信息here)
脚本并没有在ViewComponent渲染@section,视图组件 应具备的能力在@section中包含脚本,而不像 部分视图,因为组件可以在许多视图中重用,并且组件负责其自身的功能。