Home > OS >  How to get JS object and pass it back?
How to get JS object and pass it back?

Time:05-24

I would like to call JS function from Blazor (this is factory method) and then pass the obtained object back to JS (another function).

The problem is Blazor changes the object, so when I print the data of object being returned (in the first function) and the object obtained in the second function I can see the structure is different.

I don't want to modify or read this object in Blazor in any way, just get pass, that's it.

Update: please read comment by KirkWoll for more technical rephrasing. Currently I call JS function as await jsRuntime.InvokeAsync<object>(... but it does not work (as expected).

C# -- Net Standard 2.0.

CodePudding user response:

Demo and workaround

I've created this simple Blazor Fiddle (WASM 3.1) that reads a JavaScript object and then writes it back. And if you view the output in the browser console you can see the object is passed back and forth with the properties intact.

However, the function is stripped from the object. And that's because the object is passed as json and json only has properties. So it's only possible to send properties.

OP also tests if the returned object is the same as the stored global object. Yet, that will be false because these are different instances. The properties might be equal, but not the references.

A workaround

If the requirement is to pass the object by reference from one JavaScript function to another then the workaround would be to create a JavaScript function to do this directly without passing the object to Blazor. Basically, just a function that triggers the call. The workaround is included in the fiddle.

  • Related