Table of Contents
This is the default footer
This is the /Views/Home/List.cshtml View
Home Java javaTutorial [ASP.NET MVC Mavericks Road]12

[ASP.NET MVC Mavericks Road]12

Dec 30, 2016 pm 04:22 PM
asp.net mvc

[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);
}
Copy after login

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> 
}
Copy after login

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>
Copy after login

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:

[ASP.NET MVC Mavericks Road]12

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) 
...
Copy after login

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>    
} 
...
Copy after login


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:

[ASP.NET MVC Mavericks Road]12

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>
Copy after login

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();
}
Copy after login

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")
Copy after login

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:

[ASP.NET MVC Mavericks Road]12

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>
Copy after login

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" })
Copy after login

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:

[ASP.NET MVC Mavericks Road]12

Child Action

Child action 和 Patial view 类似,也是在应用程序的不同地方可以重复利用相同的子内容。不同的是,它是通过调用 controller 中的 action 方法来呈现子内容的,并且一般包含了业务的处理。任何 action 都可以作为子 action 。接下来介绍如何使用它。

在 HomeController 中添加一个 action,如下:

[ChildActionOnly]
public ActionResult Time()
{
    return PartialView(DateTime.Now);
}
Copy after login

这个 action 通过调用 PartialView 方法来返回一个 partial view。ChildActionOnly 特性保证了该 action 只能作为子action被调用(不是必须的)。

接着我们继续为这个action添加一个相应的 Time.cshtml 视图,代码如下:

@model DateTime

<p>The time is: @Model.ToShortTimeString()</p>
Copy after login


在 List.cshtml 视图中添加如下代码来调用 Time action 方法 :
...
@Html.Action("Time")
Copy after login

运行结果如下:

[ASP.NET MVC Mavericks Road]12

我们通过 @Html.Action 方法来调用了 Time action 方法来呈现子内容。在这个方法中我们只传了一个action名称参数,MVC将根据当前View所在Controller去查找这个action。如果是调用其它 controller 中的 action 方法,则需要在第二个参数中指定 controller 的名称,如下:

... 
@Html.Action("Time", "MyController")
Copy after login

该方法也可以给 action 方法的参数传值,如对于下面带有参数的 action:

... 
[ChildActionOnly] 
public ActionResult Time(DateTime time) { 
    return PartialView(time); 
}
Copy after login
我们可以这样使用 @Html.Action 方法:
... 
@Html.Action("Time", new { time = DateTime.Now })
Copy after login

 以上就是[ASP.NET MVC 小牛之路]12 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP MVC Architecture: Building Web Applications for the Future PHP MVC Architecture: Building Web Applications for the Future Mar 03, 2024 am 09:01 AM

Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

An advanced guide to PHP MVC architecture: unlocking advanced features An advanced guide to PHP MVC architecture: unlocking advanced features Mar 03, 2024 am 09:23 AM

The MVC architecture (Model-View-Controller) is one of the most popular patterns in PHP development because it provides a clear structure for organizing code and simplifying the development of WEB applications. While basic MVC principles are sufficient for most web applications, it has some limitations for applications that need to handle complex data or implement advanced functionality. Separating the model layer Separating the model layer is a common technique in advanced MVC architecture. It involves breaking down a model class into smaller subclasses, each focusing on a specific functionality. For example, for an e-commerce application, you might break down the main model class into an order model, a product model, and a customer model. This separation helps improve code maintainability and reusability. Use dependency injection

How to implement the MVC pattern using PHP How to implement the MVC pattern using PHP Jun 07, 2023 pm 03:40 PM

The MVC (Model-View-Controller) pattern is a commonly used software design pattern that can help developers better organize and manage code. The MVC pattern divides the application into three parts: Model, View and Controller, each part has its own role and responsibilities. In this article, we will discuss how to implement the MVC pattern using PHP. Model A model represents an application's data and data processing. usually,

Uncovering the success of the SpringMVC framework: why it is so popular Uncovering the success of the SpringMVC framework: why it is so popular Jan 24, 2024 am 08:39 AM

SpringMVC framework decrypted: Why is it so popular, specific code examples are needed Introduction: In today's software development field, the SpringMVC framework has become a very popular choice among developers. It is a Web framework based on the MVC architecture pattern, providing a flexible, lightweight, and efficient development method. This article will delve into the charm of the SpringMVC framework and demonstrate its power through specific code examples. 1. Advantages of SpringMVC framework Flexible configuration method Spr

How to use MVC architecture to design projects in PHP How to use MVC architecture to design projects in PHP Jun 27, 2023 pm 12:18 PM

In Web development, MVC (Model-View-Controller) is a commonly used architectural pattern for processing and managing an application's data, user interface, and control logic. As a popular web development language, PHP can also use the MVC architecture to design and build web applications. This article will introduce how to use MVC architecture to design projects in PHP, and explain its advantages and precautions. What is MVCMVC is a software architecture pattern commonly used in web applications. MV

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Sep 11, 2023 am 09:43 AM

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Introduction: With the rapid development of the Internet, Web development plays an important role in today's software development industry. PHP is widely used for web development, and there are many mature frameworks that help developers build applications more efficiently. Among them, the MVC (Model-View-Controller) architecture is one of the most common and widely used patterns. This article will introduce how beginners can use the PHP8 framework to develop MVC applications.

Developing MVC with PHP8 Framework: A Step-by-Step Guide Developing MVC with PHP8 Framework: A Step-by-Step Guide Sep 11, 2023 am 10:05 AM

Developing MVC with PHP8 Framework: A Step-by-Step Guide Introduction: MVC (Model-View-Controller) is a commonly used software architecture pattern that is used to separate the logic, data and user interface of an application. It provides a structure that separates the application into three distinct components for better management and maintenance of the code. In this article, we will explore how to use the PHP8 framework to develop an application that conforms to the MVC pattern. Step One: Understand the MVC Pattern Before starting to develop an MVC application, I

Revealing the secrets of PHP MVC architecture: Make your website fly Revealing the secrets of PHP MVC architecture: Make your website fly Mar 03, 2024 am 09:25 AM

Model-view-controller (mvc) architecture is a powerful design pattern for building maintainable and scalable WEB applications. The PHPMVC architecture decomposes application logic into three distinct components: Model: represents the data and business logic in the application. View: Responsible for presenting data to users. Controller: Acts as a bridge between the model and the view, handling user requests and coordinating other components. Advantages of MVC architecture: Code separation: MVC separates application logic from the presentation layer, improving maintainability and scalability. Reusability: View and model components can be reused across different applications, reducing code duplication. Performance Optimization: MVC architecture allows caching of view and model results, thus increasing website speed. Test Friendly: Detachment

See all articles