29 JUNE 2017
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:
They are similar to partial views but provide more power.
A view component
:
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);
}
}
@model string;
@if (Model != String.Empty)
{
<li class="nav-item">
@Model
</li>
}
@await Component.InvokeAsync("CompanyName")
// You can also add parameters if required. Add these to InvokeAsync(int maxNum)
@await Component.InvokeAsync("CompanyName", { maxNum = 4 })