How to implement drag and drop in Blazor?

blazor c# html

Question

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

Popular Answer

IMPORTANT: I believe that UIDragEventArgs is not supported at present...

... "than the default behavior is the well-known "e.preventDefault()" which should make the drop target droppable" ==> I'm not sure about that.

Here's how you've got to set your elements.
Note: The code in the methods below is in Javascript. You've got to translate it to C#  

    <div id="targetDiv" class="col" ondrop="@Add" ondragover="@AllowDrop"></div>

    <span id="draggedSpan" class="badge badge-warning" draggable="true" ondragstart="@AllowDragOver>îtem 1</span>

@functions {

void Add(UIDragEventArgs e)
{
    e.preventDefault();
    var data = e.dataTransfer.getData("text");
    e.target.appendChild(document.getElementById(data));

     Items.Add("hello");
}

void AllowDragOver(UIDragEventArgs e)
{
     e.dataTransfer.setData("text", e.target.id);
}

void AllowDrop(UIDragEventArgs e)
{
    e.preventDefault();
}

}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why