Microsoft has replaced child actions in previous MVC versions with View Components in MVC 6. Child actions are useful for when you want to build reusable widgets but they have their own limitations, one those I mentioned in my last post.
View components are similar to child actions but are lighter weight.
Create a view component
To create a view component, simply create a new class, inherit ViewComponent base class and then either implement Invoke or InvokeAsync if you want to call it asynchronously. There are two other ways to create a view component:
- Decorating a class with [ViewComponent] attribute
- Creating a class following the naming convention where the name ends with ViewComponent
View components also support constructor dependency injection, see sample view component below.
public class NewsArticlesViewComponent : ViewComponent { private readonly IArticleService articleService; public NewsArticlesViewComponent(IArticleService articleService) { articleService = articleService; } public IViewComponentResult Invoke(int pageNumber) { var articles = articleService.GetNewArticles(pageNumber); return View(articles); } }
The view component consists of a view component class, as above, and a view (similar to child actions).
@model IEnumerable<Article> <h2>News</h2> <ul> @foreach (var newsArticle in Model) { <li> @newsArticle.Title </li> } </ul>
Invoking a view component
To invoke a view component in any razor view, call @Component.Invoke or @await Component.InvokeAsynce if you implement the InvokeAsync in your view component class.
<div> @Component.Invoke("NewsArticles", new { pageNumber = 1}) <div>
or if calling it asynchronously
<div> @await Component.InvokeAsync("NewsArticles", new { pageNumber = 1}) <div>