[ASP.NET
MVC Mavericks Road]12 - Section, Partial View and Child Action
In summary, the content in View can be divided into static and dynamic parts. Static content is generally html elements, while dynamic content refers to content that is dynamically created when the application is running. The ways to add dynamic content to View can be summarized as follows:
Inline code, small code snippets, such as if and foreach statements.
Html helper method, used to generate single or multiple HTML elements, such as view model, ViewBag, etc.
Section, insert a part of the created content at the specified location.
Partial view, exists in a separate view file and can be shared among multiple views as sub-content.
Child action is equivalent to a UI component that contains business logic. When a child action is used, it calls the action in the controller to return a view and inserts the result into the output stream.
This classification is not absolute. The first two are very simple and have been used in previous articles. This article mainly introduces the applications of the latter three methods.
Directory of this article
Section
The Razor view engine supports separating part of the content in the View so that it can be reused where needed , reducing code redundancy. Let's demonstrate how to use Section.
Create an MVC application and choose a basic template. Add a HomeController, edit the generated Index method as follows:
public ActionResult Index() { string[] names = { "Apple", "Orange", "Pear" }; return View(names); }
Right-click the Index method, add a view, edit the view as follows:
@model string[] @{ ViewBag.Title = "Index"; } @section Header { <div class="view"> @foreach (string str in new [] {"Home", "List", "Edit"}) { @Html.ActionLink(str, str, null, new { style = "margin: 5px" }) } </div> } <div class="view"> This is a list of fruit names: @foreach (string name in Model) { <span><b>@name</b></span> } </div>@section Footer { <div class="view"> This is the footer </div> }
We define a @section tag plus the name of the section Section, two sections are created here: Header and Footer. It is customary to place the section at the beginning or end of the View file to facilitate reading. Below we use them in the /Views/Shared/_Layout.cshtml file.
Edit the /Views/Shared/_Layout.cshtml file as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <style type="text/css"> div.layout { background-color: lightgray;} div.view { border: thin solid black; margin: 10px 0;} </style> <title>@ViewBag.Title</title> </head> <body> @RenderSection("Header") <div class="layout"> This is part of the layout </div> @RenderBody() <div class="layout"> This is part of the layout </div> @RenderSection("Footer") <div class="layout"> This is part of the layout </div> </body> </html>
We call the content of the section through the @RenderSection method, and the parameter specifies the name of the section. After running the program, you can see the following results:
Note that section can only be called in the current View or its Layout. The @RenderSection method will throw an exception if it does not find the section specified by the parameter. If you are not sure whether the section exists, you need to specify the value of the second parameter as false, as follows:
... @RenderSection("scripts", false) ...
We can also use the IsSectionDefined method to determine a Whether section is defined or can be called in the current View, such as:
... @if (IsSectionDefined("Footer")) { @RenderSection("Footer") } else { <h4 id="This-nbsp-is-nbsp-the-nbsp-default-nbsp-footer">This is the default footer</h4> } ...
Partial View
Partial view (partial view) places some Razor and Html tags in In a separate view file for reuse in different places. Next, we will introduce how to use partial view.
Let’s create a partial view first. Create a new view file named MyPartial in the /Views/Shared directory, check "Create as partial view", as follows:
The added partial view file is An empty file, we add the following code to this file:
<div> This is the message from the partial view. @Html.ActionLink("This is a link to the Index action", "Index") </div>
This MyPartial.cshtml view will create a connection back to the homepage. Of course, the @Html.ActionLink method here is also a (Html helper) way to dynamically load View content.
Then add a List action method in HomeController, as follows:
public ActionResult List() { return View(); }
Continue to add a List.cshtml view for this, and call the part we want to present through the @Html.Partial method View, as follows:
@{ ViewBag.Title = "List"; Layout = null; } <h3 id="This-nbsp-is-nbsp-the-nbsp-Views-Home-List-cshtml-nbsp-View">This is the /Views/Home/List.cshtml View</h3> @Html.Partial("MyPartial")
The view engine will search for the MyPartial view in the /Views/Home and /Views/Shared folders in the specified order.
Run the program and navigate to /Home/List, we can see the following effect:
There is no difference between the use of Partial view and ordinary View, and Strong types can be used. For example, we specify the type of model through @model in MyPartial.cshtml:
@model IEnumerable<string> <div> This is the message from the partial view. @Html.ActionLink("This is a link to the Index action", "Index") <ul> @foreach (string str in Model) { <li>@str</li> } </ul> </div>
and modify the main view List.cshtml that calls the MyPartial.cshtml view as follows:
@{ ViewBag.Title = "List"; Layout = null; } <h3 id="This-nbsp-is-nbsp-the-nbsp-Views-Home-List-cshtml-nbsp-View">This is the /Views/Home/List.cshtml View</h3> @Html.Partial("MyPartial", new[] { "Apple", "Orange", "Pear" })
and The difference above is that here we specify the second parameter to @Html.Partial and pass an array to the model object of MyPartial.cshtml. The running effect is as follows:
Child Action
Child action 和 Patial view 类似,也是在应用程序的不同地方可以重复利用相同的子内容。不同的是,它是通过调用 controller 中的 action 方法来呈现子内容的,并且一般包含了业务的处理。任何 action 都可以作为子 action 。接下来介绍如何使用它。
在 HomeController 中添加一个 action,如下:
[ChildActionOnly] public ActionResult Time() { return PartialView(DateTime.Now); }
这个 action 通过调用 PartialView 方法来返回一个 partial view。ChildActionOnly 特性保证了该 action 只能作为子action被调用(不是必须的)。
接着我们继续为这个action添加一个相应的 Time.cshtml 视图,代码如下:
@model DateTime <p>The time is: @Model.ToShortTimeString()</p>
... @Html.Action("Time")
运行结果如下:
我们通过 @Html.Action 方法来调用了 Time action 方法来呈现子内容。在这个方法中我们只传了一个action名称参数,MVC将根据当前View所在Controller去查找这个action。如果是调用其它 controller 中的 action 方法,则需要在第二个参数中指定 controller 的名称,如下:
... @Html.Action("Time", "MyController")
该方法也可以给 action 方法的参数传值,如对于下面带有参数的 action:
... [ChildActionOnly] public ActionResult Time(DateTime time) { return PartialView(time); }我们可以这样使用 @Html.Action 方法:
... @Html.Action("Time", new { time = DateTime.Now })
以上就是[ASP.NET MVC 小牛之路]12 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor