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

Super detailed Tik Tok operation-tools!

All the practical information and skills are clos...

How to do marketing on Women’s Day? Here are 4 tips for you!

Today is International Women's Day... NO, you...

2022 Xiaohongshu user portrait insights and grass-planting analysis

The first part [User Mind Insights] mainly discus...

Guide to starting a new Tik Tok account!

1. The current situation of Douyin live streaming...

The world's deepest underground laboratory has made important progress!

Wang Jing, Wang Chao, Shen Qiushi, Science and Te...

Tik Tok’s traffic conversion rate is extremely poor! Whose fault is it?

How to divert traffic from Douyin accounts across...