View Components

View components are similar to partial views, but they're much more powerful. View components don't use model binding, they depend on the data passed when calling the view component.

  • contains logic as well as view

  • support for dependency injection

  • always linked to parent view

Usage

  • Dynamic navigation menus

  • Tag cloud, where it queries the database

  • Sign in panel

  • Shopping cart

  • Recently published articles

  • Sidebar content on a blog

  • A sign in panel that would be rendered on every page and show either the links to sign out or sign in, depending on the sign in state of the user

Creating a View Component

public class ShoppingCartSummary : ViewComponent {
    public IViewComponentResult Invoke() {
        return View(model);
    }
}

View Components Default Location

  • Controllers

  • Models

  • Views

    • Shared

      • Components

Using the View Component

@await Component.InvokeAsync("ShoppingCartSummary");

Last updated