Erik Dahl
Erik Dahl

Reputation: 488

Blazor databinding to a javascript web component with complex object from C#

I've got a Blazor app that is referencing a custom web component (<omnibar-navigation>).

This component has an items property that should be a json object that looks something like this:

[{'title':'Home','icon':'places-home-1','url':'/','metadata':null,'items':null}, ...]

I'm wondering how to bind a C# complex object to that items property.

var options = new List<Nav> { new Nav { Title = "Home", Icon = "places-home-1", Url = "/" } };

Then the binding would be something like this (doesn't work):

<omnibar-navigation items="@options">...</omnibar-navigation>

A code repo for this problem is here: https://github.com/dahlsailrunner/blazor-oidc.

The page with the exact problem is here: https://github.com/dahlsailrunner/blazor-oidc/blob/master/Sample.Blazor/Pages/Stencil.razor

The component is imported on the Pages/_Host.cshtml file. enter image description here

Upvotes: 0

Views: 1062

Answers (2)

Thomas Claudius Huber
Thomas Claudius Huber

Reputation: 236

Great question. I noticed also some issues with binding a web component directly via Blazor data binding, especially with the connectedCallback of the web component which is a kwown issue.

But the great thing is:

If something in Blazor doesn't work, you can always use JavaScript Interop to make it work!

I've created here a blog post for you that shows how to integrate a web component via JS Interop that has such a property/attribute that takes a complex object: https://www.thomasclaudiushuber.com/2020/02/14/initializing-web-components-in-blazor-via-js-interop/

It also shows how to wrap the web component with a native Blazor component, so that you can bind it just with C#. :-)

Here is a git repo with all the code: https://github.com/thomasclaudiushuber/Blazor-Using-Custom-Web-Component

Happy coding, Thomas

Upvotes: 1

Jeff Fritz
Jeff Fritz

Reputation: 9861

You're going to build a component with a Parameter property that receives an IEnumerable of your Nav type. You just need to deserialize your JSON and bind it to that collection.

Check this gist for how you can deserialize the JSON and bind to the collection in the index.razor file

https://gist.github.com/csharpfritz/c4dcfcc731826822e0764728bbd9d88c

Upvotes: 1

Related Questions