Render script block within Blazor razor component

Michael Hanlon 21 Reputation points
2022-08-21T00:51:25.243+00:00

I am a newbie to both Blazor and Javascript. I am writing a Blazor server application.

I have a script block provided by a third party...

    <script src="https://secure.ewaypayments.com/scripts/eCrypt.min.js"  
        class="eway-paynow-button"  
        data-publicapikey="XXX-XXXXXXX-XXXXXX-XXXXXX"  
        data-amount="1000"  
        data-currency="AUD">  
    </script>  

In a normal HTML page this will render a button which, when pressed will popup a secure payments window.

I realise I can place this in my _Layout.cshtml and it works as expected, but can I render it from within a Razor component?

Thank you

Developer technologies .NET Blazor
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Willem Boeré 1 Reputation point
    2022-08-21T10:09:47.133+00:00

    Hello,

    Yes this is possible.
    By adding a script tag with custom javascript or link to external javascript file. You can call these functions by using JSRuntime.InvokeAsync,

    A nice example is found here:
    https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0

    With kind regards,

    Willem

    0 comments No comments

  2. Anonymous
    2022-08-22T07:33:01.697+00:00

    Hi @Michael Hanlon ,

    In a normal HTML page this will render a button which, when pressed will popup a secure payments window.
    I realise I can place this in my _Layout.cshtml and it works as expected, but can I render it from within a Razor component?

    You can add the third party script reference in the _Layout.cshtml page, then add the normal html elements in the Razor component.

    [Note] The Razor component should use the _Layout.cshtml template page.

    Refer to the following sample:
    In the _Layour.cshtml page, add the script reference:

    233348-image.png

    In the Razor component (use the _Layout.cshtml template page), add the relates html element and the CSS selector.

    233415-image.png

    The result as below:233349-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.