Search code examples
blazormaui.net-maui

can and if yes how do elements in Javascript communicate with the C# Code?


I have Leaflet map object declared in index.html

index.html

<head>
   <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
          integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14="
          crossorigin="" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha256-o9N1jGDZrf5tS+Ft4gbIK7mYMipq9lqpVJ91xHSyKhg="
            crossorigin=""></script>
</head>

<script>
        window.displayMapJS = () => {
            var map = L.map('map').setView([51.505, -0.09], 13);

            L.tileLayer('https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=rzE5ZFAnhim5yWM3jJsC', {
                maxZoom: 19,
                attribution: '&copy; <a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'
            }).addTo(map);

            
        }
    </script>

When the app launches:

index.razor

@page "/"
@using System.Diagnostics
@inject IJSRuntime JS


<div id="map"></div>

@code{
    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            try
            {
                await JS.InvokeVoidAsync("displayMapJS");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
           
    }
}

How can I do stuff with the map object, trigger functions on the map in javascript from the C# code? Pass parameters? Get objects back?


Solution

  • This can be achived just like you did in your example code:

    await JS.InvokeVoidAsync("displayMapJS");
    

    To get a value back:

    await JS.InvokeAsync<bool>("function_that_returns_bool");
    

    I suggest that you create a new Razor Class Library type project. This template will directly generate an example of how you can use C# with JavaScript.