ASP.NET MVC 6, a new feature called view components has been introduced. View components are similar to child actions and partials views, allowing you to create reusable components with (or without) logic. Here's the summary from the ASP.NET documentation:


View components include the same separation-of-concerns and testability benefits found between a controller and view. You can think of a view component as a mini-controller—it’s responsible for rendering a chunk rather than a whole response. You can use view components to solve any problem that you feel is too complex with a partial.


Before ASP.NET Core, you would've probably used a child action to create a reusable component that requires some code for its logic. ASP.NET MVC 6, however, doesn't have child actions anymore. You can now choose between a partial view or a view component, depending on the requirements for the feature you're implementing.

Writing A Simple View Component

Let's implement a simple dynamic navigation menu as a view component. We want to be able to display different navigation items based on some conditional logic (e.g. the user's claims or the hosting environment). Like controllers, view components must be public, non-nested, and non-abstract classes that either

  • derive from the ViewComponent class,
  • are decorated with the [ViewComponent] attribute, or
  • have a name that ends with the "ViewComponent" suffix.

We'll choose the base class approach because ViewComponent provides a bunch of helper methods that we'll be calling to return and render a chunk of HTML.


ASP.NET MVC 6 Dependency Injection using a simple container that is bundled with ASP.NET MVC 6. This is great for injecting dependencies into controllers, filters, etc. In this tutorial I mention the new inject keyword that can be added to razor views for injecting dependencies into views.


Registering Service

First, we have to register the service with the IoC container built into ASP.NET MVC 6.

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddTransient<ITestService, TestService>();
}

This is no different from the previous example: ASP.NET MVC 6 Dependency Injection.

Inject Keyword for Razor Views


Next we can inject the the service for use in the razor view using the new inject keyword.

@inject ITestService testService


Now the service is available to our view and can be used appropriately anywhere in the view.

@using Sample.Services
@inject ITestService testService
<p>So I looked down and said... @testService.WhatAreThose()</p>

Conclusion

Injecting dependencies in ASP.NET MVC 6 views using the new inject keyword can make things quite a bit easier. Now that ASP.NET MVC 6 has a basic IoC container we'll probably see more people start to use dependency injection not only in their views, but also in their controllers, filters, services, etc.