Search code examples
blazorblazor-server-side

Should an inner component share the Context with its containing component?


I presently have:

<EditForm EditContext="EditContext"
          OnValidSubmit="HandleValidSubmitAsync"
          OnInvalidSubmit="HandleInvalidSubmitAsync"
          Context="formContext">

        <AddressForm @ref="_addressElement"
                     Value="Model.AddressModel"
                     Context="@EditContext"
                     ReadOnly="@(ModeState == Mode.Read)"
                     OnValidated="OnAddressValidated"
                     ValueChanged="@OnAddressChanged" />
</EditForm>

There's a problem with the above. Because it shares, then in AddressForm when I do the following:

Context.OnFieldChanged += OnFieldChanged;

To be honest, I don't remember why I did this. And I don't need it in the <AddressForm> component. But I'm wondering if I was told there's a good reason to do this and so added this.

Is sharing the Context a good thing? Bad thing? Either way?


Solution

  • I'm guessing you have something like this:

    class Member
    {
       public string FirstName
       public string LastName
       public AddressModel Addreess
       ...
    }
    
    class AddressModel
    {
       public string Town
       ....
    }
    

    If so then the issue is that EditContext basically works on a flat single layer model. It represents model fields with the FieldIndentifier readonly struct

    public object Model
    public string FieldName
    

    The Model should be the EditContext model. Here are some suggestions.

    How you deal with this is design and data pipeline specific. Here are some suggestions.

    1. Split out how you edit bits of you data - modal dialog form for the address with it's own edit context and validation model which gets validated (and save decision made) in the modal dialog form. You then update the main model by marking the field has changed if it has.

    2. Flatten your model by building a ModelEditContext class with it's own validation model. Saving then writes the data back to the complex object before saving back though the data pipeline.

    3. Use Aggregate objects that do the above and more. Too big a topic to cover here.