Javascript in a View Component

后端 未结 5 747
抹茶落季
抹茶落季 2020-12-14 02:14

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

5条回答
  •  春和景丽
    2020-12-14 02:39

    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.

提交回复
热议问题