Skip to content Skip to sidebar Skip to footer

Where Should I Include A Script For A View Component?

I have tried adding a section script inside a view component's view. @section scripts { } I also have

Solution 1:

I also had problems with sections tag in viewcomponents. Turns out, to the best of my knowledge, there is no support for it in viewcomponents. See https://github.com/aspnet/Home/issues/2037

Jake Shakesworth has implemented a tag helper as shown in: Javascript in a View Component

On the other hand you could just include it in your viewcomponent as an

<scriptdefersrc"..."></script>

My requirement was to show a google map from a viewcomponent. Problem was that the script was getting called before the jquery, jquery.ui stuff. By using defer you are telling the parser not to execute it until the document had loaded thus avoiding the problem of the having to put it in the layout for proper execution. Defer is supported by chrome, safari, and ie(10+), ff(3.6+), o(15+)

Hope this helps

This is an example of my code:

@using MobileVet.WebApp.Services;
@inject ISettingsService SettingsService
@{
     var Options = SettingsService.Value();

    <!--Service Area--><divclass="container-fluid"><divclass="row p-3"><!--First column--><divclass="col-md-3"><h5class="title">Site Navigation</h5><ul><li><ahref="#!">Home</a></li><li><ahref="#!">Services</a></li><li><ahref="#!">Link 3</a></li><li><ahref="#!">Link 4</a></li></ul></div><!--/.First column--><hrclass="w-100 clearfix d-md-none"><!--Second column--><divclass="col-md-9"><divid="map-canvas"style="min-height: 300px; min-width: 200px;"></div></div><!--/.Second column--></div></div><!--Service Area--><scriptsrc="http://maps.google.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXX&sensor=false"></script><scripttype="text/javascript"src="~/js/components/servicearea.js"defer ></script>

}

Note that you would probably need to write some logic to prevent the script to be included multiple times if the view component is present more than once on a page, which was not my case

Solution 2:

From what I have seen, a "@section Scripts {}" in a ViewComponent is ignored and does not render in the relevant @RenderSection() of the ViewComponents _*layout.cshtml

Why that is I do not know.

Solution 3:

@section scripts { } in viewcomponents is ignored and not rendered by Asp.Net rendering engine. So just use at the end of the view component. Also if your jquery scripts are at specified at the end in your layout, then jquery will not be available in your viewcomponents. Of course moving the jquery script to the head section in layout will solve the problem but it is recommended to load the js files at the end.

So if you want to keep jquery scripts at the end of layout and still use jquery in viewcomponents, you could use javascript domcontentloaded and any jquery can be written inside domcontentloaded. Not a permanent good approach but works for me.

<script>document.addEventListener('DOMContentLoaded', function (event) {
        console.log($ === jQuery)
    });
</script>

Or as mentioned by @Alberto L. Bonfiglio you could also try to move your script to another JS file and defer load it in your viewcomponent:

<scriptsrc="viewComponentScript.js"defer></script>

Solution 4:

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

<environmentinclude="Development"><scriptsrc="~/lib/jquery/dist/jquery.js"></script><scriptsrc="~/lib/moment/moment.js"></script><scriptsrc="~/lib/fullcalendar/dist/fullcalendar.js"></script><scriptsrc="~/js/calendarWidget.js"></script></environment><environmentexclude="Development"><scriptsrc="~/lib/jquery/dist/jquery.min.js"></script><scriptsrc="~/lib/moment/min/moment.min.js"></script><scriptsrc="~/lib/fullcalendar/dist/fullcalendar.min.js"></script><scriptsrc="~/js/calendarWidget.js"></script></environment>

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

<section id="calendar"></section>
@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;

namespaceLodgersChoice.ViewComponents
{
    publicclassCalendarWidgetViewComponent : ViewComponent
    {
        publicasync Task<IViewComponentResult> 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.

Solution 5:

I'm registering the ViewComponents scripts in a scoped service, the registered scripts are then rendered after the scripts section in layout.

ViewComponentsService.cs

using System;
using System.Collections.Generic;

namespaceYourProject.Services
{
    publicclassViewComponentsService
    {
        
        privatereadonly List<Func<object>> _scripts = new List<Func<object>>();

        public IEnumerable<Func<object>> Scripts {
            get { 
                foreach (var script in _scripts)
                {
                    yieldreturn script;
                }
            }
        }
        
        // A dictionary could be used as type for the _scripts collection.// Doing so a script Id could be passed to RegisterScript.// Usefull if only one script per ViewComponent type needs to be rendered.publicvoidRegisterScript(Func<object> script) {
            _scripts.Add(script);
        }

    }
}

Don't forget to register the service in startup.

services.AddScoped<ViewComponentsService>();

Example ViewComponent

Here we have the ViewComponent and its scripts in the same file!

@modelUI.FailUserFeedback@injectServices.ViewComponentsService _viewComponentsService

@{
    var modalId = UI.Utilities.RandomId();
    var labelId = UI.Utilities.RandomId();
}

<div class="modal fade" id="@modalId" tabindex="-1" aria-labelledby="@labelId" aria-hidden="true">
    @*omitted for brevity*@
</div>

@{
    // the script is written hereFunc<dynamic, object> RenderScript =
    @<script>
            (function () {
                var modal = new bootstrap.Modal(document.getElementById('@modalId'));
                modal.show();
            })();
    </script>;
    // and registered here
    _viewComponentsService.RegisterScript(() =>RenderScript(this));
}

Layout

@inject Services.ViewComponentsService _viewComponentsService
...
@await RenderSectionAsync("Scripts", required: false)
@foreach(var script in _viewComponentsService.Scripts) {
    @script();
}

Post a Comment for "Where Should I Include A Script For A View Component?"