Skip to content

Getting started

One package and one service registration - then a BdndProvider around any interactively rendered region, with draggables and drop targets inside it. You drag data of a type, not a view, and the drag state lives in C#.

Install

In a Blazor Web App with an interactive client, the package belongs in the .Client project, next to the pages that drag.

dotnet add package Bit.Bdnd

Register the service

It registers BdndInterop, the scoped wrapper around the script module that every draggable and drop target reaches the browser through, and that a component of your own can inject to measure an element. The drag-and-drop manager itself is not a service: each BdndProvider creates its own and shares it with the components inside it. In a Blazor Web App, register it in both Program.cs files - the pages are prerendered on the server before they run in the browser. Outside AOT builds, a WebAssembly app can also lazy load the library instead of registering it.

// Program.cs - in every project that renders the components
builder.Services.AddBitBdndServices();

And the namespace, in _Imports.razor:

@using Bit.Bdnd
There is no stylesheet to link and no script tag to add: the components import their module, _content/Bit.Bdnd/bit-bdnd.js, themselves the first time they need it.

A first drag and drop

Wrap the region in a BdndProvider and declare sources and targets inside it. A draggable's Type is what a target matches against its Accept list, and its Item is what the target's OnDrop receives. Each one's child content gets the collected state - IsDragging for a source, IsOver and CanDrop for a target - to render from.

Live
Glass
Banana
Paper
Drag a box here

Drag a box with the mouse, press and hold one with a finger, or Tab to it and press Space, an arrow key and Space again: the same markup takes all three.

<BdndProvider>
    <div class="row-wrap">
        @foreach (var name in _boxes)
        {
            <BdndDraggable TItem="string" Type="box" Item="name" Context="drag">
                <div class="box" style="opacity:@(drag.IsDragging ? "0.4" : "1")">@name</div>
            </BdndDraggable>
        }
    </div>

    <BdndDropTarget TItem="string" Accept="box" OnDrop="HandleDrop" Context="drop" style="display:contents">
        <div class="dustbin" style="margin-top:1.5rem;background:@(drop.IsOver ? "#15803d" : "#1f2430")">
            @(drop.IsOver ? "Release to drop" : _label)
        </div>
    </BdndDropTarget>
</BdndProvider>

@code {
    private readonly string[] _boxes = ["Glass", "Banana", "Paper"];
    private string _label = "Drag a box here";

    private void HandleDrop(BdndDropEventArgs<string> e) => _label = $"Dropped: {e.Item}";
}
Three things make this work: the components sit inside one BdndProvider; the draggable's Type is one of the types the target lists in Accept; and the page is interactive, because a statically rendered page never wires up drag events.

Core concepts

Bdnd brings React DnD's data-driven model to Blazor as components rather than hooks.

ConceptIn Bdnd
Items and types You drag an item - any C# object - of a type, a string. A target accepts the types it lists in Accept or AcceptTypes; the item's .NET type does not take part.
Components BdndProvider, BdndDraggable, BdndDropTarget, BdndDragLayer and BdndDragHandle - React DnD's provider, useDrag, useDrop, useDragLayer and a drag handle.
Collected state What a component's child content renders from: IsDragging, IsOver, IsOverShallow, CanDrop, the item and the offsets.
Monitor IBdndMonitor, a read-only view of the live drag state, on every collected state and callback argument as Monitor.
Callbacks OnBegin and OnEnd on a source; OnHover, OnEnter, OnLeave and OnDrop on a target; OnDragStart and OnDragEnd on the provider for every drag. A target can publish a result from OnDrop, which the source's OnEnd receives with DidDrop.
Input The browser's own HTML5 drag and drop for the mouse - so files, text and links dragged in from outside the browser drop too - pointer events for touch and pen, and the keyboard (Space, the arrow keys, Space) for everyone. Every input runs the same callbacks.
Styling hooks Hosts carry data-bit-bdnd-dragging, data-bit-bdnd-can-drop, data-bit-bdnd-over, data-bit-bdnd-over-shallow and data-bit-bdnd-edge while a drag is in progress, so a stylesheet can follow it. Bdnd ships no stylesheet of its own.

Lazy loading on WebAssembly

The draggables and drop targets also work without AddBitBdndServices, so a WebAssembly app can fetch Bdnd only when someone opens a part of the app that drags. When BdndInterop is not registered, they create it themselves, once per WebAssembly runtime, and IServiceProvider.GetBdndInterop() hands the app's own code the same one. Mark the assembly as lazy loaded in the project that runs in the browser, and load it before the first page that uses it renders:

<!-- The browser project's .csproj -->
<ItemGroup>
  <BlazorWebAssemblyLazyLoad Include="Bit.Bdnd.wasm" />
</ItemGroup>
@* App.razor - in a Blazor Web App, the client project's Routes.razor: the router waits for OnNavigateAsync
   before it renders the page. typeof(Program) is the project the router's file is in, in either kind of app. *@
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader

<Router AppAssembly="typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsync">
    ...
</Router>

@code {
    private async Task OnNavigateAsync(NavigationContext context)
    {
        // The pages that drag: fetch Bdnd before they render. A second call loads nothing again. Routes match
        // regardless of case, so /Board/2 is one of them too.
        if (context.Path.StartsWith("board", StringComparison.OrdinalIgnoreCase))
            await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bdnd.wasm"]);
    }
}

Those pages hold the provider, the draggables and the drop targets as usual. A component that measures an element - the card of a sortable list - takes the interop from GetBdndInterop() instead of injecting BdndInterop:

@* SortableCard.razor *@
@inject IServiceProvider Services

@code {
    // Taken once, as an injected service would be: HandleHover runs for every move over the card.
    private BdndInterop Interop => field ??= Services.GetBdndInterop();

    private async Task HandleHover(BdndDropEventArgs<DragItem> e)
    {
        var rect = await Interop.GetBoundingClientRectAsync(_element);
        ...
    }
}
  • Leave AddBitBdndServices out of that project's Program.cs: calling it references Bdnd's types before the assembly is there. For the same reason only what renders after the assembly has loaded may use Bdnd's types - the pages it is loaded for and a layout only they use, not App.razor, Routes.razor, a layout every page shares or Program.cs.
  • No type in an assembly the router reads when the app starts - the app's own assembly first of all - may derive from or implement one of Bdnd's: no component that inherits BdndProvider, BdndDragLayer or BdndDragHandle, no IBdndMonitor or IBdndDragHandleController of your own. On WebAssembly such a type fails to load before Bit.Bdnd is there, and keeps failing after it has loaded. Put it in a library that is lazy loaded together with Bit.Bdnd.
  • Nothing else changes: AddBitBdndServices takes no options, so the components behave exactly as they do with it, and they import their script module the first time they need it either way.
  • In a Blazor Web App only the browser lazy loads. Give Routes the InteractiveWebAssembly or InteractiveAuto render mode in App.razor, so the router - and its OnNavigateAsync - runs in the browser; with per-page render modes it renders statically on the server and never loads the assembly in the browser. The server project loads Bdnd with the rest of the app and keeps its AddBitBdndServices(), and registers LazyAssemblyLoader, which Routes.razor injects while it is prerendered there and which loads nothing outside the browser: builder.Services.AddScoped<LazyAssemblyLoader>().
  • Do not lazy load in an AOT build. AOT compiles every assembly into dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup.
An unhandled error has occurred. Reload 🗙