Where should I include a script for a view component?

前端 未结 5 1926
故里飘歌
故里飘歌 2021-02-20 04:26

I have tried adding a section script inside a view component\'s view.

@section scripts {
    

        
5条回答
  •  一向
    一向 (楼主)
    2021-02-20 04:40

    This is how I approached inserting scripts into a view component using Asp.net core 2.0.

    First I created a partial view which I placed inside of the view components view folder.

    Path: Views/Shared/Components/CalendarWidget/_CalendarScriptsPartial.cshtml

    _CalendarScriptsPartial.cshtml

    
        
        
        
        
    
    
        
        
        
        
    
    

    Then, I brought in the scripts via the Html partial async helper method inside of my view components view.

    Path: Views/Shared/Components/CalendarWidget/Default.cshtml

    Default.cshtml

    @await Html.PartialAsync( "Components/CalendarWidget/_CalendarScriptsPartial" )

    And for the sake of completeness here is my view components class.

    Path: ViewComponents/CalendarWidgetViewComponent.cs

    CalendarWidgetViewComponent.cs

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    
    namespace LodgersChoice.ViewComponents
    {
        public class CalendarWidgetViewComponent : ViewComponent
        {
            public async Task InvokeAsync( )
            {
                return View( );
            }
        }
    }
    

    Note: Async isn't currently required in my example but I intend to inject a repository into the ctor of the class which will be using async/await.

    Note 2: Once I'm done developing this I plan on bundling and minifying everything down to one script.

提交回复
热议问题