Nov 4

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

You can create popups in Razor Components 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 popup does not require any JavaScript code.

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

 

@page "/Popup"
<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;
    bool showDynamicPopup = false;
    void ShowSimplePopup()
    {
        showDynamicPopup = false;
        showSimplePopup = true;
    }
    void HideSimplePopup()
    {
        showSimplePopup = false;
    }
    void ShowDynamicPopup()
    {
        showSimplePopup = false;
        showDynamicPopup = true;
    }
    void HideDynamicPopup()
    {
        showDynamicPopup = 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.

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 JavaScript interop.

image

The first step is to open the index.cshtml page in the 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/', 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/)

Now, we arrive at the JavaScript interop part.

Add the following code to the top of the Popup.razor page:

 

@inject IJSRuntime JSRuntime

 

This gives us access to the JavaScript.

 

Add this button to the markup:

 

<button class="btn btn-primary" onclick="@ShowDynamicPopup">Show Dynamic Popup</button>

 

Now, add this Popup markup:

 

@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, passing it a reference to the modalBody Div element:

 

    ElementRef modalBody; // reference to the DIV
    protected override void OnAfterRender()
    {
        // This will set the content of the Div
        // to the content of the server Login page
        setDivContent(modalBody);
    }
    public Task setDivContent(ElementRef elementRef)
    {
        return JSRuntime.InvokeAsync<object>("populateDiv", elementRef);
    }

 

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

Microsoft.Interop.JSRuntime.Current has been removed

Reconsider static JSRuntime.Current

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 2019 (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