Essentially I can only pass primitives and anonymous types as argument in Blazor interop with JS.
My first post on stack overflow ever because I just cant figure this out:
This example works:
C#:
async void doThing()
{
await JSRuntime.InvokeAsync<object>("test", new { Name = "John", Age = 35 });
}
JS:
var test = funciton(stuff){
console.log(stuff);
return stuff;
}
Output in JS is object with name and age as expected.
Now here's my actual class:
public class CarsAndBikes
{
public car[] cars;
public bike[] bikes;
}
async void doThing()
{
await JSRuntime.InvokeAsync<object>("test", carsAdnBikes);
}
Its not that complex but what I can see in JS is an empty object, unless I serialise it as JSON and deserialise. car and bike are classes. C#
JsonConvert.SerializeObject(CarsAndBikes);
JS:
JSON.parse(stuff)
Then it works fine. I have no idea why I cannot pass my class to JS, does anyone know if Im doing something wrong or its a bug?
Here is a simple working demo using your code. It works, so there's something your not showing us that breaks your code. What does Car and Bike look like?
@page "/"
@inject IJSRuntime Js
<PageTitle>Index</PageTitle>
<button class="btn btn-primary" @onclick=doThing>Object</button>
<button class="btn btn-secondary" @onclick=doBookThing>Book as Object</button>
<button class="btn btn-dark" @onclick=doBook>Book</button>
<button class="btn btn-info" @onclick=doBooks>Books</button>
@code
{
async void doThing()
{
await Js.InvokeAsync<object>("test", new { ID = 1, Title = "Fred" });
}
async void doBookThing()
{
await Js.InvokeAsync<object>("test", new Book { ID = 1, Title = "Portugal" });
}
async void doBook()
{
await Js.InvokeAsync<Book>("test", new Book { ID = 1, Title = "Shaun" });
}
async void doBooks()
{
await Js.InvokeAsync<object>("test", new Catalog());
}
public class Book
{
public int ID { get; set; }
public string Title { get; set; } = string.Empty;
}
public class Catalog
{
public List<Book> Books { get; set; } = new List<Book> {
new Book { ID=10, Title="Jon" },
new Book { ID=11, Title="Spain" }
};
}
}