Nov 4

Written by: Michael Washington
11/4/2018 5:37 PM  RssIcon

You can create popups in Blazor without the need to write any JavaScript. However, when you do need to interact with JavaScript (for example to make a call in the web browser to pull in page content from another site), this article will demonstrate how it is done.

A Simple Popup

image

A simple Blazor popup does not require any JavaScript code.

For example, we can create a page in the client project using the following code:

 

@using BlazorPopUp.App.Services
@page "/popup"
@using BlazorCookieAuth.App.Shared
<h1>Popup</h1>
<button class="btn btn-primary" onclick="@ShowSimplePopup">Show Simple Popup</button>
@if (showSimplePopup)
{
    <div tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Blazor Simple Popup</h3>
                    <button type="button" class="close" onclick="@HideSimplePopup">
                        <span aria-hidden="true">X</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h2><< Popup Content >></h2>
                </div>
            </div>
        </div>
    </div>
}
@functions {
    bool showSimplePopup = false;
    void ShowSimplePopup()
    {
        showSimplePopup = true;
    }
    void HideSimplePopup()
    {
        showSimplePopup = false;
    }
}

 

image 

We can open and close the popup easily.

We can even change the content of the div containing the content to inject a Blazor component, such as the “Counter” component:

 

        <div class="modal-body">
            <h2><Counter/></h2>
        </div>

 

image

When we run the application we have a working counter component that is contained in a popup that we can open and close.

Blazor JavaScript Interop

image

Let’s say we wanted to fill the Popup with content from another page.

We could use JavaScript from the article: Getting HTML asynchronously from another page (with native JavaScript). 

We now need to call this JavaScript, pass it the web address of the page we want to retrieve, get the results of the call, and insert the contents returned into our Popup.

We now need  to use Blazor JavaScript interop.

image

The first step is to open the index.html page in the client project, and add the following code from the Getting HTML asynchronously from another page (with native JavaScript) article:

 

    <script type="text/javascript">
        // From: https://gomakethings.com/getting-html-asynchronously-from-another-page/
        var getHTML = function (url, callback) {
            // Feature detection
            if (!window.XMLHttpRequest) return;
            // Create new request
            var xhr = new XMLHttpRequest();
            // Setup callback
            xhr.onload = function () {
                if (callback && typeof (callback) === 'function') {
                    callback(this.responseXML);
                }
            };
            // Get the HTML
            xhr.open('GET', url);
            xhr.responseType = 'document';
            xhr.send();
        };
    </script>

 

This simply creates a JavaScript method called getHTML that will retrieve the contents of an HTML page.

Next we add the following additional code:

 

    <script type="text/javascript">
        var populateDiv = function (element) {
            getHTML('https://blazor.net/docs/javascript-interop.html', function (response) {
                element.innerHTML = response.documentElement.innerHTML;
            });
        };
    </script>

 

This adds a JavaScript method, called populateDiv, that when passed a ElementRef will populate it with the contents returned by the getHTML JavaScript method.

(for now we have hardcoded the page to return to be: https://blazor.net/docs/javascript-interop.html)

image

Now, we arrive at the JavaScript interop part.

We create a file called SetModalContentJs.cs using the following code:

 

using System.Threading.Tasks;
using Microsoft.AspNetCore.Blazor;
using Microsoft.JSInterop;
namespace BlazorCookieAuth.App.Shared
{
    public static class SetModalContentJs
    {
        public static Task setDivContent(this ElementRef elementRef)
        {
            return JSRuntime.Current.InvokeAsync<object>("populateDiv", elementRef);
        }
    }
}

 

This code creates a static method that can be called by our Blazor code.

This method will accept a ElementRef and pass it to the populateDiv JavaScript method created earlier.

image

We return to our Popup page and remove all the existing code.

We change the HTML markup to the following:

 

<button class="btn btn-primary" onclick="@ShowDynamicPopup">Show Dynamic Popup</button>
@if (showDynamicPopup)
{
    <div tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Blazor Dynamic Popup</h3>
                    <button type="button" class="close" onclick="@HideDynamicPopup">
                        <span aria-hidden="true">X</span>
                    </button>
                </div>
                <div ref="modalBody" class="modal-body">
                    <!-- Dynamic content will go here -->
                </div>
            </div>
        </div>
    </div>
}

 

Note that <!-- Dynamic content will go here - -> is contained in a Div.

The key thing here is that we added “ref=modalBody” to the Div.

This allows us to access the Div in our code in the functions section.

Change the functions section of the code to the following so that it gets a reference to modalBody after the control is fully rendered, and calls the setDivContent method (created earlier), passing it a reference to the modalBody Div element:

 

@functions {
    ElementRef modalBody; // reference to the DIV
    protected override void OnAfterRender()
    {
        // This will set the content of the Div
        SetModalContentJs.setDivContent(modalBody);
    }
}

 

Finally, add the following code that will handle opening and closing the Popup:

 

    bool showDynamicPopup = false;
    void ShowDynamicPopup()
    {
        showDynamicPopup = true;
    }
    void HideDynamicPopup()
    {
        showDynamicPopup = false;
    }

 

image

We can now click the Show Dynamic Popup button to display the Popup with the dynamically retrieved content.

 

Links

Blazor.net

Blazor JavaScript interop

Getting HTML asynchronously from another page (with native JavaScript)

 

Download

The project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

You must have Visual Studio 2017 (or higher) installed to run the code.

Tags: Blazor
Categories:

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation