.NET Core – View Components

A View Component is a great feature to use if you need to render some business-logic derived view code within a shared page, such as a layout page. It’s an effective replacement for Child Actions, which do not exist in .NET Core MVC.

There are 3 pieces to a View Component implementation:

  1. The ViewComponent derived Class which contains your business logic
  2. A view that corresponds to your ViewComponent
  3. The invocation of your ViewComponent’s Invoke method to render the html

First, we need to create a ViewComponent.

If your app doesn’t already have one, create a ViewComponents folder in your application at the same level as Models and Controllers.

2018-09-19_8-55-49

Next, create a class in this folder that is properly namespaced and derived from ViewComponent. The naming convention for this class should be EntityViewComponent.

namespace my_app.ViewComponents
{
    public class TitleViewComponent : ViewComponent
    {
        private Models.Models db;

        public TitleViewComponent(Models.Models db)
        {
            this.db = db;
        }

        public IViewComponentResult Invoke()
        {
            var tehParams = this.db
                .Set<Models.institution_parameters>()
                .FromSql("tc_get_institution_parameters", new object[] { })
                .ToList();

            ViewData["InstitutionName"] = tehParams.Where(p => p.nm == "Institution Name").First().value;

            return View();
        }
    }
}

The Invoke() method contains the business logic to query a database and stored data via ViewData or ViewBag for consumption by the returned View.

Next, in your Views/Shared/ folder, create a new subfolder that corresponds to your new ViewComponent. In our case, this folder will be named “Title”. Within this new “Title” subfolder, place a new cshtml file called Default.cshtml.

2018-09-19_9-01-54

Edit your new Default.cshtml to contain whatever HTML you want rendered when you invoke your ViewComponent, leveraging whatever ViewBag or ViewData data you exposed in your Invoke() call, in this case, a very simple view containing a name of an institution:

<div>
<b>@ViewData["InstitutionName"]</b>
</div>

Finally, we need to invoke our ViewComponent from a view, in our case, the _Layout.cshtml file:

<title>@await Component.InvokeAsync("Title")</title>

Our example doesn’t pass any parameters, but you can include parameters with your InvokeAsync() call that would be passed to the ViewComponent’s Invoke() method.