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
Sections only work in a View don't work in partial views or View Component (
Default.cshtml
executes independently of the mainViewResult
and itsLayout
value isnull
by default. ) and that's by design.
You can use it to render sections
for a Layout
that the partial view
or view component's
view declares. However, sections defined in partials and view components don't flow back to the rendering view or it's Layout.
If you want to use jQuery or other library reference in your partial view or View component then you can pull your library into head
rather than body
in your Layout
page.
Example:
View Component:
public class ContactViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
Location of ViewComponent:
/Views/[CurrentController]/Components/[NameOfComponent]/Default.cshtml
/Views/Shared/Components/[NameOfComponent]/Default.cshtml
Default.cshtml:
@model ViewComponentTest.ViewModels.Contact.ContactViewModel
_Layout.cshtml :
...
@RenderSection("styles", required: false)
@RenderBody()
...
//script move to head
@RenderSection("scripts", required: false)
View.cshtml:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
..................
@{Html.RenderPartial("YourPartialView");}
..................
@await Component.InvokeAsync("Contact")
..................
@section Scripts {
}
View Component by grahamehorner: (you can more information here)
The @section scripts don't render in a ViewComponent, view component should have the ability to include scripts within the @section unlike partital views as components may be reused across many views and the component is responsible for it's own functionality.