Invoke a C# instance method from within a static method in Blazor using DotNet.invokeMethodAsync called by JavaScript

Is it possible to invoke a non-static method from a static method in a Blazor application while changing a C# property value from JavaScript using DotNet.invokeMethodAsync? I have the following code working so far:

JS File:

[script.js]

function ChangeContentJS() {
    DotNet.invokeMethodAsync('InvokeFromJsApp', "ChangeParaContentValue", "New Content");
}

Razor page:

     [Index.razor]
    
    @page "/"
    
    @inject IJSRuntime JSRuntime
    
    <h1>Change C# property value from JavaScript</h1>
    <br />
    <button @onclick='ButtonClickHandler'>Change Content - JS</button>
    <br />
    <p>@ParaContent</p>
    
    @code {
        public static string ParaContent = "Some Text Content"; 

        public async Task ButtonClickHandler()
        {
            await JSRuntime.InvokeAsync<string>("ChangeContentJS");
        }
    
        [JSInvokable]
        public static void ChangeParaContentValue(string value)
        {
            ParaContent = value;
            RunNewCode(); //DOESNT WORK AS ITS A NON-STATIC METHOD
        }

        public void RunNewCode()
        {
           jsRuntime.InvokeVoidAsync("RunFunction");
        }
    }

I am facing issues trying to run a non-static method within a static method in a Blazor application. How can I achieve this?

When attempting to make the following method static, I encountered the error below:

  public static void RunNewCode()
            {
               jsRuntime.InvokeVoidAsync("RunFunction");
            }

CS0120: An object reference is required for the nonstatic field, method, or property 'JSRuntime'

How do I make this static: @inject IJSRuntime JSRuntime

Answer â„–1

The information you need can be found in the official documentation

To summarize: Create a static Action for the update and register the local instance

@implements IDisposable

...

private static Func<string, Task>? ChangeParaContentActionAsync;

private async Task LocalChangeParaContentValueAsync(string value)
{
    ParaContent = value;
    await jsRuntime.InvokeVoidAsync("RunFunction");
}

protected override void OnInitialized()
{
    base.OnInitialized();
    ChangeParaContentActionAsync = LocalChangeParaContentValueAsync;
}

// There are no guarantees that disposal works properly in this case. It may even be called during initialization
public void Dispose()
{
    ChangeParaContentActionAsync = null:
}

[JSInvokable]
public static async Task ChangeParaContentValue(string value)
{
    if (ChangeParaContentActionAsync is {} actionAsync)
    {
        await actionAsync(value);
    }
}

(not tested)

NOTE: Keep in mind that you can still call the JSInvokable method even if the component is not loaded (no instance). This could lead to undefined behavior!

Edit: Changed to async Task, due to the asynchronous nature of InvokeVoidAsync method

Answer â„–2

Here is a possible solution that worked for me, although I am unsure if it is the best approach:

private static CurrentRazorComponentClassName _app;

public CurrentRazorComponentClassName ()
{
    _app = this;
}

[JSInvokable]
public static void UpdateTextInBlazor(string text)
{
    jsText = text;
    contentEditable = false;
    _app.StateHasChanged();
}

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

Deleting a directory with files using Renci SSH.NET

Currently, I am utilizing Renci SSH.NET for accessing files and directories on a unix server. My goal is to delete an entire directory tree by indicating the base directory. However, the issue arises when I use sftp.DeleteDirectory(destination), as it will ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

How can I create two interconnected search inputs with React Hooks to efficiently filter results?

If my explanation is not clear, please let me know so I can provide further clarification. I currently have two search input fields. One is for sorting by name and the other is for sorting by tags. Filtering names from an API was straightforward, but filt ...

What is the best charting component, tool, or library for JavaScript or ASP.NET that would be suitable for this

[Update]: Oops, forgot to mention ComponentArt... Hello, A client I am working with provided some mock-ups created by their interaction designer, and now I am tasked with deciding how to implement the charts shown in the designs. After researching and e ...

Optimizing nested collections with JavaScript arrays of boolean values

I have multiple nested collections of JavaScript objects and I believe there has to be a more efficient way to achieve what I'm doing. The goal is to access the values of the fields in Objects 1, 2, and 3 and check if they are true or false. Below is ...

Utilizing Cytoscape JS in Conjunction with JHipster Angular

I've encountered an issue while trying to integrate the plain JavaScript library, cytoscapejs, into my Angular application created with JHipster. I went ahead and installed the library using npm, then added the JS file to my vendor.ts file. However, w ...

What is the correct method for inserting a div block?

Here is some code that I have which converts simple text to a textarea field: $('.field').on({ mouseenter: function() { title='<?php echo $user_title; ?>&ap ...

Calculate the total length of the nested arrays within an object

Check out this object: const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] } I'm looking to find a way to quickly calculate the sum of lengths of arrays arr1 and arr2. ...

Server-side access to form data has been restricted

When I make a PUT request from the frontend, I am currently using the XMLHttpRequest and FormData API. However, on the server side, I am not receiving any data such as req.params, req.body, and req.query are all empty. Front-end Implementation var report ...

Adding a javascript file to a Vue component

I am currently working on a project that involves using Laravel and Vue.js. In order to incorporate an image editing package called "photojshop" into my Vue component, I tried the following approach: <template> <img src=".." id="myImg" > </ ...

Tips for embedding query values within a mongoose query

I have a database in MongoDB that contains an array with company names. I need to remove a specific element from the array based on its position. So, I crafted a query to achieve this. { company: [ {name: "exist"}, {name: "cool"}, {name: "h ...

Can a Nuxt 2 project support the coexistence of both JavaScript and TypeScript?

I am currently working on a project in Nuxt 2.17.2 that is entirely written in JavaScript, but now I need to integrate some SDKs that are written in TypeScript. My goal is to configure the project in a way that allows me to seamlessly run both TypeScript ...

What is the best way to obtain the clicked ID when a user clicks on an element within

As a budding web developer, I've been working on a code snippet to dynamically load data into an iframe: $(document).ready(function () { function loadMaterials(type, query) { $.ajax({ type: 'GET', url: &ap ...

What is the process for incorporating Visual Basic power packs references into a C# Windows Form project?

I just added the Visual Basic Power Packs package to my project and I'm trying to reference the VisualBasic.PowerPacks dll, but it doesn't seem to be showing up. I'm using VS 2012. Any help would be appreciated. Thank you! ...

Using the Loop Function in Node.js with EJS Templates

Seeking help with a node.js application that utilizes bootstrap. I am trying to display the bootstrap cards in rows of 3, with each row containing data from my dataset in columns. However, my current implementation using two for loops is leading to repeate ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

Tips for updating the URL in the browser address bar after loading content using AJAX with angular.js

When developing a web application using angular.js, the communication within the app is done through AJAX. This means that when the application requests web resources, the URL in the browser address bar does not change. For instance, my app displays build ...

What is the best way to create and save an Excel file using Node.js, then how can I facilitate

I am looking to extract data from a database and save it to an Excel file. I am using the xlsx library, but I encountered an issue when trying to open the file: Excel cannot open the file ****.xlsx because the file format or file extension is not valid ...

Just getting started with Apache Cordova: build unsuccessful

I've been attempting to develop an Android app using JavaScript with Apache Cordova. Despite following all the steps and installing the necessary components, I'm encountering an issue during the build process: C:\Users\qiova\cordo ...