Popular blog tags

Loading View Components from a Class Library in ASP.NET Core MVC application

Published

Originally posted to: http://www.davepaquette.com/archive/2016/07/16/loading-view-components-from-a-class-library-in-asp-net-core.aspx

share Library

step 1. Creating a class library

 

step 2.add a view component class to the project

[ViewComponent(Name = "ViewComponentLibrary.Simple")]
public class SimpleViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(int number)
    {
        return View(number + 1);
    }
}

step 3.added a Default.cshtml view to the ViewComponentLibrary in the Views\Shared\Components\Simple folder

@model Int32

<h1>
    Hello from an external View Component!
</h1>
<h3>Your number is @Model</h3>

step 4.For this view to be recognized by the web application, we need to include the cshtml files as embedded resources in the class library. Currently, this is done by adding the following setting to the project.json file.

"buildOptions": {
    "embed": "Views/**/*.cshtml"
}

How to use

step 1.Referencing external view components

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();

    //Get a reference to the assembly that contains the view components
    var assembly = typeof(ViewComponentLibrary.ViewComponents.SimpleViewComponent).GetTypeInfo().Assembly;

    //Create an EmbeddedFileProvider for that assembly
    var embeddedFileProvider = new EmbeddedFileProvider(
        assembly,
        "ViewComponentLibrary"
    );

    //Add the file provider to the Razor view engine
    services.Configure<RazorViewEngineOptions>(options =>
    {                
        options.FileProviders.Add(embeddedFileProvider);
    });
}

step 2.invoke the view component  in  ASP.NET Core MVC application.

<div class="row">
    @await Component.InvokeAsync("ViewComponentLibrary.Simple", new { number = 5 })
</div>

 

 

https://github.com/iaspnetcore/wwwiaspnetcorecom/blob/363cc9fa33ad782e606d459ee701f3b4398df1d1/src/ProjectMenuLibrary/MenuWebApp/MenuWebApp.csproj

 

You can take a look at the full source code on GitHub. https://github.com/AspNetMonsters/ExternalViewComponents

Create reusable UI using the Razor class library project in ASP.NET Core

https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-9.0&tabs=visual-studio