Search code examples
c#bindblazor

How to bind input value to object property in Blazor


I have a object property like this: public object Data { get; set; }

And I have some input with different types in .razor component:

switch (DataType)
{
    case DataType.Boolean:
        <input @bind="Data" type="checkbox" />
        break;
    case DataType.String:
        <input @bind="Data" type="text" />
        break;
    case DataType.Number:
        <input @bind="Data" type="number" />
        break;
}

Аs a result I get error:

The type System.Object does not have an associated TypeConverter that supports conversion from a string

how can I bind these input to object property?


Solution

  • I had a similar problem and using @onchange instead of @bind resolved it.

    switch (DataType)
    {
        case DataType.Boolean:
            <input @onchange="@(x => { Data = x; })" type="checkbox" />
            break;
        case DataType.String:
            <input @onchange="@(x => { Data = x; })" type="text" />
            break;
        case DataType.Number:
            <input @onchange="@(x => { Data = x; })" type="number" />
            break;
    }