Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

inheritance - Is there a way to change the model on a Blazor EditForm Component depending on user selection?

I have a class called Client and two classes that inherit from it ClientCompany and ClientPerson, I have a blazor EditForm to add an edit clients and depeding on the type of client the user chooses (Company or Person) I would like to bind the form and the controls to the corresponding class and its properties.

I want to do this on the same form because the parent class Client has a lot of fields but ClientCompany and ClientPerson only a few so if I create two diferent blazor components for each class I would be repeating code.

So I would like to know If Is there a way to change the binding model for the EditForm and their controls depending on a a radiobutton selection, so if user selects Person bind the EditForm to ClientPerson but if the user selects Company bind the EditForm to ClientCompany.

I'm using .net 5, Blazor Web Assembly and Entity Framework.

question from:https://stackoverflow.com/questions/66056442/is-there-a-way-to-change-the-model-on-a-blazor-editform-component-depending-on-u

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<EditForm EditContext="@EditContext" OnValidSubmit="HandleValidSubmit">

</EditForm>

@code
{
    private EditContext EditContext;
    private Client client= new Client() { };

    protected override void OnInitialized()
    {
        EditContext = new EditContext(client);

        base.OnInitialized();
    }
}

As you can see, you can initially initialize the EditContext object with an instance of the Client class, and when your user make a choice, you can initialize the EditContext instance with a new instance of EditContext, like this:

ClientCompany client= new ClientCompany () { };

EditContext = new EditContext(client);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...