What is @RenderSection in asp.net MVC - Stack Overflow
What is the purpose of @RenderSection and how does it function? I understand what bundles do, but I have yet to figure out what this does and it's probably important.
@RenderSection("scripts", required: false)
Perhaps a small example on how to use it?
回答1
If you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
the required indicates whether or not the view using the layout page must have a scripts section
回答2
Supposing that:
1. You have a _Layout.cshtml
view like this.
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
2. You have Contacts.cshtml
.
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
3. You have About.cshtml
.
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
On your layout page, if required
is set to false
: @RenderSection("scripts", required: false)
, when the page renders and the user is on the about page, contacts.js
won't render.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
If required
is set to true
: @RenderSection("scripts", required: true)
, When page renders and user is on the About page, contacts.js
still gets rendered.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
IN SHORT, when set to true
, whether you need it or not on other pages, it will get rendered anyhow. If set to false
, it will render only when the child page is rendered.
标签:RenderSection,What,asp,false,cshtml,required,scripts,page From: https://www.cnblogs.com/chucklu/p/17767358.html