Home > other >  How to load a JS library in Blazor server razor file?
How to load a JS library in Blazor server razor file?

Time:12-04

I'm trying to follow the document HERE to load THIS bootstrap-datepicker within a blazor server app. Note: I want to load it for a single page only without having to load it for all pages.

Within the .razor file I'm trying to do this:

HTML

<input @ref=ReferenceToInputControl  id="obdInput">

Code

@code {
    ElementReference ReferenceToInputControl;
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            jsModule = await JS.InvokeAsync<IJSObjectReference>("import", "./js/bootstrap-datepicker.js");
            await jsModule.InvokeVoidAsync("Datepicker", ReferenceToInputControl);
        }
    }

}

I get an error that "Could not find Datepicker. Datepicker was undefined".

I've read so much information about IIFE and scope and closure and modules but I can't for the life of me figure out what I need to do with that function so it will load and I can use it to change the input into a calendar.

CodePudding user response:

That library isn't using ES Modules, so import won't work. The way it's distributed, it's designed to be loaded in a script tag:

<script type="text/javascript" src="js/bootstrap-datepicker.min.js"></script>

You'll also need the CSS from the same repo, as well as jQuery and Bootstrap.

However it's worth noting that that library is fairly old, does not have Bootstrap 5 support, and will need some adjustments to use with Bootstrap 3 or 4 see here.

CodePudding user response:

To load a JavaScript library in a Blazor Server Razor file, you can use the @section directive to define a section of your Razor file that will be rendered in the HTML tag. You can then use the @Html.Raw method to include the JavaScript library in the section.

For example, if you want to load the jQuery library in your Blazor Server Razor file, you can use the following code:

@section head {
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
}

In this example, the head section is defined in the Razor file, and the tag is used to include the jQuery library in the section. When the Razor file is rendered, the tag will be included in the HTML tag, which will load the jQuery library in the page.

You can use this approach to load any JavaScript library in your Blazor Server Razor file. Simply define the head section and use the @Html.Raw method to include the tag for the library in the section. This will ensure that the library is loaded in the page when the Razor file is rendered.

You can learn more about the @section directive and the @Html.Raw method in the Blazor documentation: https://docs.microsoft.com/en-us/aspnet/core/blazor/layouts?view=aspnetcore-3.1.

  • Related