Interpreting ASP.NET 5 & MVC6 Series (14): View Component

Interpreting ASP.NET 5 & MVC6 Series (14): View Component

In previous MVC, we often need a function similar to a widget, and usually we use Partial View to achieve it, because MVC does not have a function similar to WebControl in Web Forms. But in MVC6, this function has been greatly improved. In the new version of MVC6, a function called View Component is provided.

You can think of View Component as a mini Controller - it is only responsible for rendering a small part of the content, not the entire response. All problems that Partial View can solve can be solved by View Component, such as: dynamic navigation menus, Tag tags, login windows, shopping carts, recently read articles, etc.

View Component consists of two parts, one is a class (inherited from ViewComponent), and the other is a Razor view (same as a normal View view). Just like the Controller in the new version of MVC, ViewComponent can also be a POCO (that is, it does not inherit the ViewComponent class, but the class name ends with ViewComponent).

Creation of View Component

Currently, there are three ways to create a View Component class:

Directly inherits from ViewComponent

Add the ViewComponent attribute to a class, or inherit from a class with the ViewComponent attribute

Create a class with the name ending with ViewComponent

Like Controller, View Component must be public, cannot be nested, and cannot be an abstract class. For example, we create a View Component with the class name TopListViewComponent, and the code is as follows:

  1. public   class TopListViewComponent : ViewComponent
  2. {
  3. private readonly ApplicationDbContext db;
  4.  
  5. public TopListViewComponent(ApplicationDbContext context)
  6. {
  7. db = context;
  8. }
  9.  
  10. public IViewComponentResult Invoke( int categoryId, int topN)
  11. {
  12. List col = new List(); var items = db.TodoItems.Where(x => x.IsDone == false && x.categoryId == categoryId).Take(topN); return View(items); } }
  13.  
  14.   

The above class can also be defined as follows:

  1. [ViewComponent(Name = "TopList" )]
  2. public   class TopWidget
  3. {
  4. // Other similar  
  5. }

By defining a ViewComponent attribute named TopList on the TopWidget class, the effect is the same as defining the TopListViewComponent class. The system will recognize it when searching, and prompt the type instance of the parameter in the constructor through the dependency injection function in its constructor.

The Invoke method is a convention method that can pass in any number of parameters. The system also supports the InvokeAsync method to implement asynchronous functions.

View Component view file creation

Taking calling View Component in the view of ProductController as an example, we need to create a folder named Components under the Views\Product folder (the folder name must be Components).

Then create a folder named TopList in the Views\Product\Components folder (the folder name must be consistent with the View Component name, that is, it must be TopList).

In the Views\Product\Components\TopList folder, create a Default.cshtml view file and add the following markup:

  1. @model IEnumerable < BookStore.Models.ProductItem >  
  2.  
  3. < h3 > Top Products </ h3 >  
  4. < ul >  
  5. @foreach (var todo in Model)
  6. {
  7. < li > @todo.Title </ li >  
  8. }
  9. </ ul >  

If the view name is not specified in the View Component, the default view is Default.cshtml.

At this point, the View Component is created. You can call the View Component anywhere in the Views\Product\index.cshtml view, for example:

  1. < div   class = "col-md-4" >  
  2. @Component.Invoke("TopList", 1, 10)
  3. </ div >  

If the asynchronous method InvokeAsync is defined in the above TopListViewComponent, you can use the @await Component.InvokeAsync() method to call it. The first parameter of these two methods is the name of the TopListViewComponent, and the remaining parameters are the method parameters defined in the TopListViewComponent class.

Note: Generally speaking, the view files of View Component are added to the Views\Shared folder, because ViewComponent is generally not specific to a certain Controller.

Using custom view files

Generally speaking, if you want to use a custom file, you need to specify the name of the view when the Invoke method returns the return value. The example is as follows:

  1. return View("TopN", items);

Then, you need to create a Views\Product\Components\TopN.cshtml file, and you don’t need to change it when using it. Just specify the original View Component name, for example:

  1. @await Component.InvokeAsync("TopList", 1, 10) //Take asynchronous call as an example

Summarize

Generally speaking, it is recommended to use the View Component function on common functions, so that all view files can be placed in the Views\Shared folder.

<<:  Interpreting ASP.NET 5 & MVC6 Series (12): Strongly Typed Routing Implementation Based on Lamda Expressions

>>:  Interpreting ASP.NET 5 & MVC6 Series (15): MvcOptions Configuration

Recommend

Apple iOS 15 Messages App has a bug that causes saved photos to be deleted

September 30 News Messages is a feature update la...

iOS13.5 performance test: Do 5 old iPhones run faster after upgrading?

Apple has officially launched the official versio...

The little opossum can carry babies, play dead, and resist poison...

At the Tokyo Olympics, balance beam champion Guan...

Controller or remote control? Where is the future of TV game peripherals?

The booming development of TV games has also allo...

How to design a good operation activity?

In addition to working hard on visual design, ope...

How can a small brand turn into a big brand?

In the past, if a small brand wanted to turn arou...

Four marketing techniques for jewelry industry on Xiaohongshu

Some time ago, a friend of mine on Xiaohongshu to...

How to follow mini programs on WeChat? Where are WeChat’s mini-apps?

Nowadays, the application scope of mini programs ...

What is the focus of content operations? One picture tells you!

Without further ado, the whole article is structu...

2017, the Warring States Period of information flow advertising!

The information entrance of mobile Internet has c...

Learn about Afghanistan in 30 seconds!

This article was first published by Hunzhi (WeCha...

How to acquire seed users without money or resources?

When a new product is just starting to operate, I...

What does the job content of Douyin operation include? What skills are required?

Many people actually want to do Douyin operation ...