0

We can assign and re-use the TValue with help of typeparam in the Blazor platform. But, how will we assign the TValue dynamically for Blazor InputNumber component?

code example:

[index.razor]

<EditForm>

      @*The below definiton is working*@
      <InputNumber TValue="int?" @bind-Value="@DynamicModelInstance.ValueAsT"></InputNumber>
       @*The below definiton is not working*@
    <InputNumber TValue="DynamicModelInstance.Type" @bind-Value="@DynamicModelInstance.ValueAsT"></InputNumber>
</EditForm>
@code {
    public DynamicModel<int> DynamicModelInstance { get; set; }

    protected override void OnInitialized()
    {
        DynamicModelInstance = new DynamicModel<int>();
        DynamicModelInstance.ValueAsT = 500;
    }
}

[DynamicModel.cs]

namespace CustomComponent.Pages
{
public class DynamicModel<T> where T : struct
{
    public System.Type Type { get; set; }
    public bool Enabled { get; set; }

    public DynamicModel()
    {
        this.Type = typeof(T);
    }

    private T _value;

    public T ValueAsT
    {
        get { return (T)_value; }
        set { this._value = value; }
    }
}
}

How to achieve this requirement?

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

0

The issue was your EditForm:

EditForm requires either a Model parameter, or an EditContext parameter

<EditForm Model="dynamicModelInstance">
    <InputNumber @bind-Value="@dynamicModelInstance!.Value" />
</EditForm>
@code {
    public DynamicModel<int>? dynamicModelInstance;

    protected override void OnInitialized()
    {
        dynamicModelInstance = new()
        {
            Value = 500
        };
    }
}
public class DynamicModel<T> where T : struct
{
    public T Value { get; set; }
}

Brian Parker
  • 11,946
  • 2
  • 31
  • 41
  • Even though we specified Modal or EditContext i could not specify the TValue dynamically. It shows the below error. The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?) – Berly Christopher Dec 10 '21 at 06:31