Javascript in a View Component

后端 未结 5 748
抹茶落季
抹茶落季 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:43

    Sections only work in a View don't work in partial views or View Component (Default.cshtml executes independently of the main ViewResult and its Layout value is null 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
    
    
    Contact Email:
    Name:
    Message:

    _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.

提交回复
热议问题