Attributes and TagHelpers for rendering static assets (.js
) associated with ViewComponents.
- Install the
AspNetCore
package into the ASP.NET Core Mvc project:
dotnet add package BizStream.AspNetCore.ViewComponentAssets
OR
<PackageReference Include="BizStream.AspNetCore.ViewComponentAssets" Version="x.x.x" />
- Configure services in the
Startup.cs
of the Mvc project:
using BizStream.AspNetCore.ViewComponentAssets;
using Microsoft.Extensions.DependencyInjection;
// ...
public void ConfigureServices( IServiceCollection services )
{
services.AddMvc()
// support ViewComponentAssets annotations/tag helpers
.AddViewComponentAssets();
}
public void Configure( IApplicationBuilder app, IWebHostEnvironment environment )
{
// ...
}
- Annotate a
ViewComponent
:
using BizStream.AspNetCore.ViewComponentAssets.Annotations;
using Microsoft.AspNetCore.Mvc;
namespace MyComponents;
[ViewComponentScript("/scripts/my-view-component.js")]
public class MyViewComponent : ViewComponent
{
public override IViewComponentResult Invoke( ) => Content( "Hello, World!" );
}
- Use TagHelpers in Views:
@using MyComponents;
@addTagHelper *, BizStream.AspNetCore.ViewComponentAssets
<body>
@(await Component.InvokeAsync<MyViewComponent>())
<view-component-scripts />
</body>
- Rendered HTML contains
<script />
elements forViewComponentScript
s:
<body>
Hello, World!
<script src="/scripts/my-view-component.js" />
</body>