How to implement drag and drop in Blazor?

blazor c# html


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

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?


9/20/2018 1:25:57 PM

Accepted 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.


Here is the promised demo on Github:

10/15/2018 4:03:58 PM

Popular Answer

Yes, we all know that it is possible to call Javascript functions from Blazor components. That was not the issue. You did not make your code available. However, if you circumvent Blazor, and get your code works by using JavaScript, this is not the way to go. This reminds of a user who tried to create a treeview in Blazor, implementing the treeview purely by JavaScript. I've suggested otherwise, and at last he succeeded to create the treeview without using any JavaScript at all. Which is what we have to strive for: minimizing the use of JavaScript and using C# on the client. See the treeview here:Blazor two-way bind not detected when is updated from JS

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow