Consider the following Blazor markup:
<div class="drag-drop-area @this.Conditional(isDragging, "drag-over")"
@ondragenter="OnDragEnter"
@ondragenter:preventDefault
@ondragleave="OnDragLeave"
@ondragleave:preventDefault
@ondrop="OnDrop"
@ondrop:preventDefault>
<div class="h3 text-secondary">
<i class="fa-solid fa-download"></i>
<p>Drop a file here</p>
</div>
</div>
private bool isDragging = false;
private void OnDragEnter(DragEventArgs e)
{
isDragging = true;
StateHasChanged();
}
private void OnDragLeave(DragEventArgs e)
{
isDragging = false;
StateHasChanged();
}
private void OnDrop(DragEventArgs e)
{
isDragging = false;
StateHasChanged();
}
The events are being respected because I can see the styles changing when the mouse enters or leaves the drag-drop-area
, but preventDefault
is not respected. Specifically, I want to drop CSV files into that region and access their data (that's the next challenge), but all this does is downloads the CSV file into my ~/user/Downloads
directory.
Any ideas how to fix this?
Note: I am using C# 12, .NET 8, and Interactive Server rendering.
You could try implement ondragover
event and also set preventDefault to true like following:
<div class="drag-drop-areä"
@ondrop="OnDrop"
@ondrop:preventDefault="true"
@ondragover="OnOver"
@ondragover:preventDefault="true">
<div class="h3 text-secondary">
<i class="fa-solid fa-download"></i>
<p>Drop a file here</p>
</div>
</div>
@code{
private bool isDragging = false;
private void OnDrop(DragEventArgs e)
{
var files = e.DataTransfer.Files;
isDragging = false;
StateHasChanged();
}
private void OnOver(DragEventArgs e)
{
}
}