Confused about Blazor two-way data binding with collections and complex objects #56490
Unanswered
UniMichael
asked this question in
Q&A
Replies: 1 comment
-
Found an issue with this approach. Unfortunately, I'd really appreciate if someone could comment on the recommended approach for binding complex objects. As it stands, Blazor seems too immature for any serious project if it can't handle a simple use case like dealing with objects. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've gone through the Blazor data binding documentation, but I'm confused about how complex objects and lists (of complex objects) are meant to work with data binding.
Imagine the following scenario:
You have an
Address
class and aPerson
class:Let's say I want to create a re-usable component that modifies a
Person
instance and its addresses. Maybe this component has some built-in validation for its fields, or runs some kind of logic when certain properties are updated.What's the recommended approach to take here?
Right now I've been toying with the following approach:
This is how it would work in something like React, where the top-level component has the state, and either wraps its
setState()
function in more specialized callbacks or passes it outright to its children so they can update the nested-state properly.With this approach, we need to explicitly "bubble up" our nested property change events, though.
This seems to work (and I've been considering using
record
s instead ofclass
es so I can use thewith
keyword to create copies with only the affected property being changed), but it still feels weird.Our components update the parameter's properties directly, and then signal to the parent that the parameter itself should be changed (even though it hasn't). I've added
Console.WriteLine()
s to most of our components to track how the lifecycle methods trigger when I make a change, and the whole component hierarchy re-renders (which makes sense when the top-level component is told to update its bound[Parameter]
). I don't know enough about Blazor's inner workings to know if this is problematic or not.The only alternative I've been able to think of for cases with complex objects is to have a flattened model and individually bind every property. But that doesn't really work if I have a list with an unknown size. One approach I've seen people take with lists is to just keep it at the top-level and bind the individual values, but that doesn't really solve the issue of having a list of complex objects or a complex objects with lists inside of it.
Data binding's easy enough with trivial models and data types, but it seems to fall apart with collections and complex objects, and the documentation doesn't seem to offer guidance on how to deal with this.
So what's the recommended approach for this?
Beta Was this translation helpful? Give feedback.
All reactions