Tips for transferring a DotNetObjectReference to a JS DOM event

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.

Answer №1

Here is some rough pseudo code I quickly jotted down in Notepad, so please excuse any errors. This code demonstrates how to call into JavaScript and send data back to C#.

In a JavaScript file:

window.myBlazor = {
    doSomething: function(cSharpObjectReference, val1, val2) {
    // perform some JavaScript tasks
    cSharpObjectReference.Notify(someData);
}

In a C# file:

public static class MyInterops
{
private static readonly string _BaseObjectContainer = "myBlazor";
        public static async Task DoSomethingCs(IJSRuntime jsRuntime, ObjectJavaScriptShouldUse cSharp, MyModel model)
        {
            await jsRuntime.InvokeVoidAsync($"{_BaseObjectContainer}.doSomething", DotNetObjectReference.Create(cSharp), model.Val1, model.Val2);
        }
}


public class ObjectJavaScriptShouldUse 
{
    private readonly IJSRuntime _jsRuntime;
    [JSInvokable]
    public async ValueTask Notify(MouseEvent eventArgs)
    {
       await MyInterops.DoSomethingCs(_jsRuntime, this, eventArgs); // Please note, there may be recursion here
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

Is Next.js Dynamic Routing Failing You?

Recently, I attempted to implement Dynamic routing for a recipe app but encountered an issue where the page was not found. This problem has left me puzzled as I am fairly inexperienced with TypeScript, although not with React. // pages/recipes/[recipeId].t ...

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

Error encountered in VUE JS 3: The function vue.initDirectivesForSSR is not recognized as a valid function

I've been encountering some errors while trying to build my Vue web app with this configuration. I have searched for a solution, but couldn't find anyone facing the same issue as me. Any suggestions on how to resolve this problem? The build was s ...

Is there a way to use Javascript or JQuery to conceal all unchecked items in a RadioButtonList?

Currently, I am utilizing the Asp .net repeater to bind the selected value in the RadioButton list. Here is an example snippet: <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Eval("Numbers& ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...

Determining the optimal emSize for a font to ensure text perfectly fits within a designated area

I've been struggling with this issue for quite some time now, and I could really use some assistance. I'm working on a project using PDFsharp and I need to insert a watermark into a PDF document that is downloaded via my asp.net web application. ...

Incorporating React components into your current Django project

My goal is to enhance the interactivity of a specific part of my Django website by incorporating React components into the template HTML file. Instead of replacing the entire template with React, I want to focus on integrating React for its ease in handlin ...

Maximizing Efficiency of Vendor Bundle in Angular 2 with Webpack

My MEAN application's client side is built in Angular2 with Webpack, but I'm facing slow loading times due to a large vendor modules JS file. Is there a way to optimize this situation? I want to separate the vendor's JS file. Below is my we ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, s ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...

What is the reason behind ValidatorValidate() validating all RequiredFieldValidator controls on the page?

Can you explain why the function ValidatorValidate(v) validates all the RequiredFieldValidator controls on the page instead of just executing for RequiredFieldValidator1? Here is the code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> ...

When would this be required within JavaScript or Angular?

Being new to JavaScript, I have come across information stating that the value of this changes based on how a function is invoked. However, I am confused about when it is necessary to use this and when it is not. Some code examples I've seen utilize t ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

"Adding content to the DOM using AJAX, the data is showing up as plain text rather than formatted

As part of my project, I am working on incorporating data retrieved through an AJAX request into the DOM to be able to manipulate it further. However, I encountered an issue where the data displayed as a string instead of HTML when appended to the DOM. Bel ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

How does a web worker behave when the owner is not actively engaged?

[edit: I am using Chrome 49.0.2623.112 m (64-bit) with default settings and HTTPS, but the issue occurred before the switch.] My application utilizes web workers to handle AJAX polling. While this may not provide a significant performance boost, it does e ...