I have a View Component that contains some jQuery in the Razor (.cshtml) file. The script itself is quite specific to the view (deals with some some configuration of third-p
Let's say you have components A
and B
, you could keep a _Scripts
partial view inside the components folder:
Views
Shared
Components
A
Default.cshtml
_Scripts.cshtml
B
Default.cshtml
_Scripts.cshtml
In your page (where you render the components), you could just do this for each component you use:
@await Component.InvokeAsync("A")
@await Component.InvokeAsync("B")
@section Scripts {
@await Html.PartialAsync("~/Views/Shared/Components/A/_Scripts.cshtml", Model);
@await Html.PartialAsync("~/Views/Shared/Components/B/_Scripts.cshtml", Model);
}
Inside the _Scripts
partial you put whatever you'd like inside the Scripts
section.
I would not recommend for complex pages in which you have too many components. Can be useful for few components, or where the name of the component being loaded is dynamic.