One form to capture input but two different models (typecasting with bind-Value fails)

Viewed 40

I have two models, both of which share same attributes except one, thus, I created an abstract class that has all the common attributes and made the two model classes inherit from it:

public abstract class MainModel {
    public string foobar;
    public string foo;
}
public class X : MainModel {
    public string bar;
}
public class Y : MainModel {
    public string baz;
}

Since they share almost all the same attributes, I created one MudForm (or InputForm, to that matter) that captures input from the user:

<MudForm @ref="_MudForm" Model="MainModel">

MainModel is declared and initialized in the base component class as the following (along with the component parameter that is passed along when the component is used):

[Parameter]
public bool IsX {get; set}
public MainModel MainModel { get; set; }

protected override void OnInitialized()
{
    if (IsX)
    {
        MainModel = new X();
    }
    else
    {
        MainModel = new Y();
    }
}

In the text field where the input to be received from the user differs, I am casting from the parent class instance to the child class type, doing the following (in the .razor file):

@if(MainModel is X){
    <MudTextField T="string" @bind-Value="@((X)MainModel.bar)" />
}
else if(MainModel is Y) {
    <MudTextField T="string" @bind-Value="@((Y)MainModel.baz)" />
}                

However, this does not work, as I am getting the following error (for X and Y):

Cannot convert type 'string' to 'X'

One way to overcome this is instead creating two forms, but that will duplicate code a lot. What would be the best solution to this problem?

1 Answers

It turned out that the syntax I was using for casting was incorrect. The correct syntax is as follows, for example, for the case of the first cast, it would be:

@bind-Value="((X)MainModel).bar"

Got this answer from Juan Blanco.

Related