My goal is to implement JS drag & drop in Blazor, which is working well overall. However, I am facing an issue where I want to set a custom drag image during the ondragstart
event. Below is a snippet of my code:
<div class="some-draggable-container"
draggable="true"
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)')" >
</div>
Element.dragStartHandler = function(event, imgSrcBase64) {
var img = new Image();
img.src = imgSrcBase64;
event.dataTransfer.setDragImage(img, 0, 0);
}
The issue I am facing is that I need to call a .Net function after setting the drag image, but I am unable to pass the necessary DotNetObjectReference
to the JS part.
Simply passing the newly created objectRef into the JS event call results in an Unexpected end of input
error.
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)', @(DotNetObjectReference.Create(this)))"
Using the JsonSerializer
also does not solve the issue, as it does not include the necessary DotNet.invokeMethod()
methods.
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)', @(JsonSerializer.Serialize(DotNetObjectReference.Create(this))))"
Trying to handle the event fully in .Net is not an option because the passed DragEventArgs
are not compatible with JS.
Passing the event args through IJSRuntime
into a JS function leads to errors due to differences between the native JS event and the .Net implementation.
I am looking for a solution that does not involve complicated workarounds and unnecessary complexity. Is there a better way to achieve this functionality?
Edit
As @MisterMagoo mentioned in a now deleted comment: It would be a sufficient way to pass the DotNetObjectReference
during the first cycle of OnAfterRender
to the JS part along with a static guid for reference later if needed.
However, I am concerned about the performance implications of this approach, especially with a list containing ~50-100 entries. In smaller cases, this method may work, but it may not be optimal for my scenario.
Edit
To clarify my decision to tackle this issue using JS in the first place: I am aware that I could achieve the desired functionality entirely in Blazor by creating an image that follows the cursor. However, using JS allows me to leverage the browser's native drag image functionality for better performance. This is crucial for our application, which operates within a narrow performance window.