[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>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>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>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("Time", new { time = DateTime.Now })
以上就是[ASP.NET MVC 小牛之路]12 的内容,更多相关内容请关注PHP中文网(www.php.cn)!