Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138249

Blazor javascript interop - object conversion from js to .NET

$
0
0

I am using Blazor javascript interop (js call to .NET), as in

//js
dotNetObjRef.invokeMethodAsync("DotNetMethod", jsObject);
---------------------------------------------------------
//C#
[JSInvokable]
public void DotNetMethod(object jsObject)
{
    Console.WriteLine($"jsObject type is {jsObject.GetType()}");
}

in the browser console, I get:

'jsObject type is SimpleJson.JsonObject'

Now I would like to cast jsObject to a concrete SimpleJson.JsonObject, as in

[JSInvokable]
public void DotNetMethod(object jsObject)
{
    JsonObject jsObject = (JsonObject)jsObject; //error
}

but all my trials using C# community implementations of SimpleJson (like https://github.com/facebook-csharp-sdk/simple-json) fail complaining that the cast is not valid.

As a workaround I go through strings:

//js
dotNetObjRef.invokeMethodAsync("DotNetMethod", JSON.stringify(jsObject));
.
//C#
[JSInvokable]
public void DotNetMethod(string jsObjectJSON)
{
    JsonObject jsObject = SimpleJson.DeserializeObject<JsonObject>(jsObjectJSON);
}

Does anyone know whether it is possible (and how) to use the received jsObject directly, i.e. avoiding the serialization/deserialization (and without reflection)?


Viewing all articles
Browse latest Browse all 138249

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>