Add/Load Components Dynamically in ASP.NET Blazor

@page "/somepage"

@dynamicComponent()

@functions{
  RenderFragment dynamicComponent() => builder =>
    {
        builder.OpenComponent(0, typeof(SurveyPrompt));
        builder.AddAttribute(1, "Title", "Some title");
        builder.CloseComponent();
    };
}

References
https://stackoverflow.com/questions/50188680/add-load-components-dynamically
https://github.com/dotnet/aspnetcore/issues/16104
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-6.0

Get Current URL in a Blazor Component

protected override async Task OnInitializedAsync()
{
    NavigationManager.LocationChanged += NavigationManagerOnLocationChanged;
    // access to uri on first page load
    Logger.LogInformation(NavigationManager.ToBaseRelativePath(NavigationManager.Uri));
}

private void NavigationManagerOnLocationChanged(object? sender, LocationChangedEventArgs e)
{
    // access to uri on change
    Logger.LogInformation(NavigationManager.ToBaseRelativePath(NavigationManager.Uri));
}

References
https://stackoverflow.com/questions/50102726/get-current-url-in-a-blazor-component

Set up Automapper in ASP.NET Core

Add the main AutoMapper Package to your solution via NuGet.

Add the AutoMapper Dependency Injection Package to your solution via NuGet.

Create a new class for a mapping profile. (I made a class in the main solution directory called MappingProfile.cs and add the following code.) I’ll use a User and UserDto object as an example.

public class MappingProfile : Profile {
     public MappingProfile() {
         // Add as many of these lines as you need to map your objects
         CreateMap<User, UserDto>();
         CreateMap<UserDto, User>();
     }
 }

Then add the AutoMapperConfiguration in the Startup.cs as shown below:

public void ConfigureServices(IServiceCollection services) {
    // .... Ignore code before this

   // Auto Mapper Configurations
    var mapperConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mapperConfig.CreateMapper();
    services.AddSingleton(mapper);

    services.AddMvc();

}

To invoke the mapped object in code, do something like the following:

public class UserController : Controller {

    // Create a field to store the mapper object
    private readonly IMapper _mapper;

    // Assign the object in the constructor for dependency injection
    public UserController(IMapper mapper) {
        _mapper = mapper;
    }

    public async Task<IActionResult> Edit(string id) {

        // Instantiate source object
        // (Get it from the database or whatever your code calls for)
        var user = await _context.Users
            .SingleOrDefaultAsync(u => u.Id == id);

        // Instantiate the mapped data transfer object
        // using the mapper you stored in the private field.
        // The type of the source object is the first type argument
        // and the type of the destination is the second.
        // Pass the source object you just instantiated above
        // as the argument to the _mapper.Map<>() method.
        var model = _mapper.Map<UserDto>(user);

        // .... Do whatever you want after that!
    }
}

References
https://stackoverflow.com/questions/40275195/how-to-set-up-automapper-in-asp-net-core

Get an element by ID or Class in Blazor

Blazor doesn’t manipulate the DOM directly at C# side. You cancall the JavaScript method by using JavaScript Interop to get an element by ID or class.

  • The getElementsByClassName() method returns a collection of all elements in the document with the specified class names.
  • The getElementById() method returns a collection of all elements in the document with the specified ID names.
@page "/"
@inject IJSRuntime JsRuntime

<h1 id="headingElement">Hello, world!</h1>

<p class="para-element">Welcome to your new app.</p>

@code {
    protected override async void OnAfterRender(bool firstRender)
    {
        await JsRuntime.InvokeVoidAsync("elementId");
    }
}
<body>
      . . .
      . . .

      <script>
        function elementId() {
            // Get element with the specified ID name
            var idValue = document.getElementById("headingElement");
            console.log(idValue.innerHTML);
            // Get element with the specified Class name
            var classValue = document.getElementsByClassName("para-element");
            console.log(classValue[0].innerHTML);
        }
    </script>
</body>

References
https://www.syncfusion.com/faq/blazor/javascript-interop/how-do-i-get-an-element-by-id-or-class-in-blazor

ASP.NET Core Blazor Server with Entity Framework Core

appsettings.Development.json

{
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
    "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

Database access

using var context = new MyContext();

return await context.MyEntities.ToListAsync();
if (Loading)
{
    return;
}

try
{
    Loading = true;

    ...
}
finally
{
    Loading = false;
}

New DbContext instances

builder.Services.AddDbContextFactory<ContactContext>(opt =>
    opt.UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"));
private async Task DeleteContactAsync()
{
    using var context = DbFactory.CreateDbContext();
    Filters.Loading = true;

    if (Wrapper is not null && context.Contacts is not null)
    {
        var contact = await context.Contacts
            .FirstAsync(c => c.Id == Wrapper.DeleteRequestId);

        if (contact is not null)
        {
            context.Contacts?.Remove(contact);
            await context.SaveChangesAsync();
        }
    }

    Filters.Loading = false;

    await ReloadAsync();
}

Scope to the component lifetime

@implements IDisposable
@inject IDbContextFactory<ContactContext> DbFactory
public void Dispose()
{
    Context?.Dispose();
}
protected override async Task OnInitializedAsync()
{
    Busy = true;

    try
    {
        Context = DbFactory.CreateDbContext();

        if (Context is not null && Context.Contacts is not null)
        {
            var contact = await Context.Contacts.SingleOrDefaultAsync(c => c.Id == ContactId);

            if (contact is not null)
            {
                Contact = contact;
            }
        }
    }
    finally
    {
        Busy = false;
    }

    await base.OnInitializedAsync();
}

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-6.0

Redirect to Login Page if User is not Logged In in ASP.NET Blazor

@inject NavigationManager NavigationManager

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @{
                        NavigationManager.NavigateTo("Login",true);
                    }
                </NotAuthorized>
            </AuthorizeRouteView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1"/>
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

MainLayout.razor

@code{ 

    [CascadingParameter] protected Task<AuthenticationState> AuthStat { get; set; }

    protected async override Task OnInitializedAsync()
    {
        base.OnInitialized();
        var user = (await AuthStat).User;
        if(!user.Identity.IsAuthenticated)
        {
            NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
        }
    }
}

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0#customize-unauthorized-content-with-the-router-component
https://stackoverflow.com/questions/60840986/blazor-redirect-to-login-if-user-is-not-authenticated

Force Page Reload or Refresh in Blazor

A page is reloaded/refreshed automatically at a specified interval using “NavigationManager” in OnAfterRender() method. Here the NavigateTo(“url”, forceLoad: true) method, is used to force load the browser based on the URI.

@inject NavigationManager uriHelper;

@using System.Threading;

<h1>Hello, world!</h1>

Welcome to your new app.

@code {
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            var timer = new Timer(new TimerCallback(_ =>
            {
                uriHelper.NavigateTo(uriHelper.Uri, forceLoad: true);
            }), null, 2000, 2000);
        }
    }
}

References
https://www.syncfusion.com/faq/blazor/general/how-do-i-force-page-reload-or-refresh-in-blazor

Dispose Components in Blazor

Synchronous IDisposable

@implements IDisposable

...

@code {
    ...

    public void Dispose()
    {
        obj?.Dispose();
    }
}

Asynchronous IAsyncDisposable

@implements IAsyncDisposable

...

@code {
    ...

    public async ValueTask DisposeAsync()
    {
        if (obj is not null)
        {
            await obj.DisposeAsync();
        }
    }
}

Event handlers

Always unsubscribe event handlers from .NET events.

@implements IDisposable

<EditForm EditContext="@editContext">
    ...
    <button type="submit" disabled="@formInvalid">Submit</button>
</EditForm>

@code {
    ...

    private EventHandler<FieldChangedEventArgs>? fieldChanged;

    protected override void OnInitialized()
    {
        editContext = new(model);

        fieldChanged = (_, __) =>
        {
            ...
        };

        editContext.OnFieldChanged += fieldChanged;
    }

    public void Dispose()
    {
        editContext.OnFieldChanged -= fieldChanged;
    }
}

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#synchronous-idisposable
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#asynchronous-iasyncdisposable
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#event-handlers
https://www.syncfusion.com/faq/blazor/components/how-can-i-properly-dispose-a-component-in-blazor

Detect CSS Media Query Changes in ASP.NET Blazor

dotnet add package BlazorPro.BlazorSize 

Add a reference to the namespace in your _Imports.razor or at the top of a page.

@using BlazorPro.BlazorSize

In startup.cs register ResizeListener with the applications service collection.

services.AddMediaQueryService();

Add the MediaQueryList

Add a MediaQueryList to your application’s main layout or root. The MediaQueryList is responsible for communicating with all MediaQuery components in your app. The MediaQueryList component will consolidate redundant media queries and manage resources so that unused event listeners are disposed of properly.

<MediaQueryList>
    <div class="sidebar">
        <NavMenu />
    </div>

    <div class="main">
        <div class="top-row px-4">
            <a href="http://blazor.net" target="_blank" class="ml-md-auto">About</a>
        </div>

        <div class="content px-4">
            @Body
        </div>
    </div>
</MediaQueryList>

Add a MediaQuery and bind

Using the @bind-Matches directive we can easily bind to a browser’s media query and respond to it.

@if (IsSmall)
{
    <WeatherCards Data="forecasts"></WeatherCards>
}
else
{
    <WeatherGrid Data="forecasts"></WeatherGrid>
}

@if (IsMedium)
{
    <span>Medium</span>
}

<MediaQuery Media="@Breakpoints.OnlyMedium" @bind-Matches="IsMedium" />
<MediaQuery Media="@Breakpoints.SmallDown" @bind-Matches="IsSmall" />

@code {
    WeatherForecast[] forecasts;

    bool IsMedium = false;
    bool IsSmall = false;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
    }
}

No-Code Templates

The MediaQuery component can also use templates instead of the @bind directive. Templates are useful for swapping out UI bits when the screen size changes.

<MediaQuery Media="@Breakpoints.SmallDown">
    <Matched>
        <WeatherCards Data="forecasts"></WeatherCards>
    </Matched>
    <Unmatched>
        <WeatherGrid Data="forecasts"></WeatherGrid>
    </Unmatched>
</MediaQuery>

Helpers

Common media queries are already included as helpers to keep you out of the Bootstrap docs. Stay in your code longer and write cleaner statements too!

/// @media(min-width: 576px) { ... }
/// Small devices (landscape phones, 576px and up)
IsSmallUpMedia = await listener.MatchMedia(Breakpoints.SmallUp);

/// @media(min-width: 768px) { ... }
/// Medium devices (tablets, 768px and up)
IsMediumUpMedia = await listener.MatchMedia(Breakpoints.MediumUp);

// Large devices (desktops, 992px and up)
/// @media(min-width: 992px) { ... }
IsLargeUpMedia = await listener.MatchMedia(Breakpoints.LargeUp);

/// Extra large devices (large desktops, 1200px and up)
/// @media(min-width: 1200px) { ... }
IsXLargeUpMedia = await listener.MatchMedia(Breakpoints.XLargeUp);

/// Extra small devices (portrait phones, less than 576px)
/// @media(max-width: 575.98px) { ... }
IsXSmallDown = await listener.MatchMedia(Breakpoints.XSmallDown);

/// Small devices (landscape phones, less than 768px)
/// @media(max-width: 767.98px) { ... }
IsSmallDown = = await listener.MatchMedia(Breakpoints.SmallDown);

/// Medium devices (tablets, less than 992px)
/// @media(max-width: 991.98px) { ... }
IsMediumDown = = await listener.MatchMedia(Breakpoints.MediumDown);

/// Large devices (desktops, less than 1200px)
/// @media(max-width: 1199.98px) { ... }
LargeDown = = await listener.MatchMedia(Breakpoints.LargeDown);

/// Small devices (landscape phones, 576px and up)
/// @media(min-width: 576px) and(max-width: 767.98px) { ... }
IsSmallOnly = = await listener.MatchMedia(Breakpoints.OnlySmall);

/// Medium devices (tablets, 768px and up)
/// @media(min-width: 768px) and(max-width: 991.98px) { ... }
IsMediumOnly = = await listener.MatchMedia(Breakpoints.OnlyMedium);

/// Large devices (desktops, 992px and up)
/// @media(min-width: 992px) and(max-width: 1199.98px) { ... }
IsOnlyLarge = = await listener.MatchMedia(Breakpoints.OnlyLarge);

/// <summary>
/// Combines two media queries with the `and` keyword.
/// Values must include parenthesis.
/// Ex: (min-width: 992px) and (max-width: 1199.98px)
Breakpoints.Between(string min, string max)

Example:
string BetweenMediumAndLargeOnly => Breakpoints.Between(Breakpoints.MediumUp, Breakpoints.LargeDown);
// out: "(min-width: 768px) and (max-width: 1199.98px)"

IsBetweenMediumAndLargeOnly = await listener.MatchMedia(BetweenMediumAndLargeOnly);

Listening for the Resize event

The ResizeListener is a service that allows your application to listen for the browser’s resize event. The ResizeListener is a throttled to improve performance and can be adjusted thru configuration. If you only need to respond the user’s device or screen size the MediaQueryList & MediaQuery components provide a more performant experience.

Configure DI

In startup.cs register ResizeListener with the applications service collection.

services.AddScoped<ResizeListener>();
//services.AddResizeListener(options =>
//                            {
//                                options.ReportRate = 300;
//                                options.EnableLogging = true;
//                                options.SuppressInitEvent = true;
//                            });

Usage

This example shows how to get the browsers width/height and check for media query matches. Depending on the matched media query the view can toggle between two components WeatherGrid or WeatherCards.

@inject IResizeListener listener
@implements IDisposable
@page "/fetchdata"

@using BlazorSize.Example.Data
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates adaptive rendering of a Blazor UI.</p>

<h3>Height: @browser.Height</h3>
<h3>Width: @browser.Width</h3>
<h3>MQ: @IsSmallMedia</h3>

@if (IsSmallMedia)
{
    
    <WeatherCards Data="forecasts"></WeatherCards>
}
else
{
    
    <WeatherGrid Data="forecasts"></WeatherGrid>
}

@code {
    WeatherForecast[] forecasts;

    // We can also capture the browser's width / height if needed. We hold the value here.
    BrowserWindowSize browser = new BrowserWindowSize();

    bool IsSmallMedia = false;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }

    protected override void OnAfterRender(bool firstRender)
    {

        if (firstRender)
        {
            // Subscribe to the OnResized event. This will do work when the browser is resized.
            listener.OnResized += WindowResized;
        }
    }

    void IDisposable.Dispose()
    {
        // Always use IDisposable in your component to unsubscribe from the event.
        // Be a good citizen and leave things how you found them. 
        // This way event handlers aren't called when nobody is listening.
        listener.OnResized -= WindowResized;
    }

    // This method will be called when the window resizes.
    // It is ONLY called when the user stops dragging the window's edge. (It is already throttled to protect your app from perf. nightmares)
    async void WindowResized(object _, BrowserWindowSize window)
    {
        // Get the browsers's width / height
        browser = window;

        // Check a media query to see if it was matched. We can do this at any time, but it's best to check on each resize
        IsSmallMedia = await listener.MatchMedia(Breakpoints.SmallDown);

        // We're outside of the component's lifecycle, be sure to let it know it has to re-render.
        StateHasChanged();
    }

}

References
https://www.nuget.org/packages/BlazorPro.BlazorSize