ASP. NET Core MVC Learning View Component (View Component)

  • 2021-11-13 01:11:42
  • OfStack

1. Introduction to the view component

The view component is a new feature of ASP. NET Core MVC, similar to partial views, but more powerful. The view component does not use model binding and only depends on the data provided when it is called.

View Component Features:

Be a block, not a whole response

Include the same concerns and testability benefits found between controllers and views

You can have parameters and business logic

Usually called from the layout page

The view component can be used in any situation that requires duplication of logic and is too complex for a partial view, such as:

Dynamic navigation menu

Tag cloud (need to query database)

Login panel

Shopping cart

A recently published article

Sidebar content on a typical blog

The login panel that will appear on each page displays links to log out or log in based on the user's login status

A view component consists of two parts, a class (usually derived from ViewComponent) and the result it returns (usually a view). Like Controller 1, the view component can be POCO, but most of them take advantage of methods and properties derived from ViewComponent.

2. Create a view component

(1) View component classes

A view component class can usually be created in any of the following ways:

Derived from ViewComponent

Decorate a class with the [ViewComponent] attribute, or derive from a class with the [ViewComponent] attribute

Create a class with a name suffix ending in ViewComponent

Like Controller 1, the view component must be an public, non-nested, and non-abstract class. The view component name is the class name with the ViewComponent suffix removed and can be specified using the ViewComponentAttribute. Name property.

Benefits of view component classes:

Full support for constructor dependency injection

Does not participate in the controller life cycle, which means that filters cannot be used in view components

(2) View component method

The view component defines its logic in the InvokeAsync method and returns IViewComponentResult. Parameters come directly from the call of the view component, not from the model binding. The view component never processes requests directly. Typically, the view component initializes the model and passes it to the view by calling the View method. In summary, the view component has the following characteristics:

Defines an InvokeAsync method and returns an IViewComponentResult.

Typically, the model is initialized and passed to the view by calling the ViewComponent View method.

Parameters come from the calling method, not HTTP, and there is no model binding.

It cannot be accessed directly as an HTTP endpoint, it is called from your code (usually in view). The view component does not process requests.

Overloads on the signature, not any details of the current HTTP request.

(3) View search path

The runtime searches for views in the following paths:

Views/ < controller_name > /Components/ < view_component_name > / < view_name >

Views/Shared/Components/ < view_component_name > / < view_name >

The default view name for the view component is Default, which means that your view file is usually named Default. cshtml. You can specify a different view name when you create a view component result or when you call the View method.

3. Call the view component

To use the view component, call @ Component. InvokeAsync ("View Component Name") from the view, < Anonymous parameter > ). Parameters are passed to the InvokeAsync method. As follows:


@await Component.InvokeAsync("TopicRankList",new { days=5})

A view component is usually called from a view, but it can also be called directly from a controller method, although a view component does not define an endpoint like a controller.

public ActionResult Index()
{
return ViewComponent("TopicRankList", new { days = 5 });
}

4. Practical View Component

Add 1 ViewCompoents folder, then add the UserRankList class:


public class UserRankList : ViewComponent
 {
  private readonly DataContext _db;
  private IMemoryCache _memoryCache;
  private string cacheKey = "topicrank";

  public UserRankList(DataContext db, IMemoryCache memoryCache)
  {
   _db = db;
   _memoryCache = memoryCache;
  }

  public IViewComponentResult Invoke(int days)
  {
   var items = new List<User>();
   if (!_memoryCache.TryGetValue(cacheKey, out items))
   {
    items = GetRankUsers(10, days);
   }
   _memoryCache.Set(cacheKey,items,TimeSpan.FromMinutes(10));
   return View(items);
  }

  private List<User> GetRankUsers(int top, int days)
  {
   return _db.User.OrderBy(o => o.Id).Take(top).ToList();
  }
 }

The view component class can be in any folder of the project. The [ViewComponent] attribute can change the name used to reference the view component, for example, you can name the class XYZ and apply the [ViewComponent] attribute:


[ViewComponent(Name="UserRankTop")]
public calss XYZ:ViewComponent

The Invoke method returns the list and then creates the view component view.

Create the View/Shared/Components folder. This folder must be named Components. Then create the UserRankList folder inside and add the Default. cshtml view:


@model List<MVCTest.Models.User>

<h2>user</h2>
<div class="list-group">
 @foreach (var item in Model)
 {
  <label>@item.Name</label>
 }
</div>

Finally, call in the view: @await Component.InvokeAsync("UserRankList", new { days=5})

Summarize


Related articles: