C# – How to implement drag and drop in Blazor

blazorchtml

I know Blazor is a new technology. Its current release states v0.5.1

However I'm currently implementing a PoC for a new web application.
We'd like to have the feature drag&drop in the app.
I tried to implement it the Blazor way but it does not work.

My droptarget:

<div class="col" ondragstart="@AllowDragOver" ondrop="@Add">

And the draggable item:

<span class="badge badge-warning" draggable="true">îtem 1</span>

The Blazor C# code:

@functions {

void Add()
{
     Items.Add("hello");
}

void AllowDragOver(UIDragEventArgs e)
{
}

}

The problem is that the drop target does not show in the browser as a drop target:

Drag Drop in browser

What I've read so far is that when attaching an event handler to a Blazor C# function (e.g. ondragstart) than the default behavior is the well-known "e.preventDefault()" which should make the drop target droppable.

Does anyone know how to fix this?

Sven

Best Answer

I'd like to post my solution.

What I've found out so far is that dataTransfer.setData currently does not work in Blazor 0.5.1. I can workaround this with saving the dragged element in a shared C# class that is injected as a DI service. The container needs to have the call to "e.preventDefault()" to be a valid drop target. Though this is not possible in C# you easily can call this as pure Javascript:

<div class="col-sm-1" dropzone="move" ondragenter="@(e => OnContainerDragEnter(e))" ondragover="event.preventDefault();" ondragleave="@(e => OnContainerDragLeave(e))"
 ondrop="@(e => OnContainerDrop(e, Date))" style="@_highlightColor;@_highlightDropTargetStyle">

Drag and drop works pretty good with C# and very smooth without flickering and interruptions. I will create a simple working example in the next days.

UPDATE:

Sorry, my example is already outdated and currently I haven't enough time to maintain this demo along with its source. So I'd like to add a link to a working demo from Chris Sainty: https://chrissainty.com/investigating-drag-and-drop-with-blazor/