<< Back to Blog

29 JUNE 2017

.NET Core: Using View-Component to render dynamic page content

An ASP.NET Core View component allows you to render a piece of dynamic content across multiple pages on a site, such as an Account Name in the navbar. View components are intended to be used anywhere you have reusable rendering logic that is too complex for a partial view, such as:

  • Dynamic navigation menus

They are similar to partial views but provide more power.

A view component:

  • Renders a chunk of a web page rather than a whole response.
  • Includes the same separation-of-concerns and testability benefits found between a controller and view.
  • Can have parameters and business logic.
  • Is typically invoked from a layout page.

Usage

  1. In Views/Shared, add a ‘Components’ folder.
  2. Add classes in here with names always ending in ‘ViewComponent.cs’. E.g. CompanyNameViewComponent.cs.
  3. Each View Component should have a constructor, an InvokeAsync() method, and inherit from ViewComponent.
public class CompanyNameViewComponent : ViewComponent
{
    private readonly ApplicationDbContext dbContext;
    private readonly UserManager<ApplicationUser> userManager;

    public CompanyNameViewComponent(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
    {
        this.dbContext = dbContext;
        this.userManager = userManager;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        string companyName = String.Empty;
        var user = await _userManager.GetUserAsync(HttpContext.User);
        var userFull = _dbContext.Users.Where(x => x.Id == user.Id).FirstOrDefault();
        if (userFull != null)
        {
            companyName = userFull.CompanyName;
        }

        return View("CompanyName", companyName);
    } 
}
  1. Then add a view to Views/Shared/Components/CompanyName/CompanyName.cshtml
@model string;

@if (Model != String.Empty)
{
    <li class="nav-item">
        @Model
    </li>
}
  1. To call the component from the _Layout page add the following line.
@await Component.InvokeAsync("CompanyName")

// You can also add parameters if required. Add these to InvokeAsync(int maxNum)
@await Component.InvokeAsync("CompanyName", { maxNum = 4 })