Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Blazor, fill 0 value binded property as empty string in input

Hi I have a question,

I'm experimenting with Blazor and it has been fun but I was wondering when I bind a simple model, with one int property to a text input for example:

<input type="text" class="communication__control--input" id="broadcast-port" autocomplete="off" placeholder=" " @bind="@this.Simple.Number" />

Now property in model is just int (not nullable) so default value would be 0 for that input. So my question is can I make that 0 will show as an empty string in input and still if I write any value (for example 3 will show as 3 but 0 will show empty string) to it it will bind?

Basing @Bennyboy1973 comment, basically I could go with 2 properties one that will be binded string prop and other would be read only int that will try to convert first one, or just use 2 model combination (something like DTO and backend model) with Automapper. But is there any simpler way?

Upvotes: 1

Views: 2327

Answers (2)

Traxo
Traxo

Reputation: 19002

Use a nullable value type, for example decimal? instead of decimal

<input @bind="price" placeholder="0.00" type="text" />

@code {
    public decimal? price = null;
}

Upvotes: 0

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30074

If you really want to do it this way, then this works:

    <input type="text" @bind-value="model.Value" />

@code {

    public class Model
    {
        public string Email { get; set; }

        public string Value
        {
            get => _value != 0 ? _value.ToString() : string.Empty;
            set
            {
                if (int.TryParse(value, out int pvalue))
                    _value = pvalue;
                else
                    _value = 0;
            }
        }

        private int _value;
    }

I can foresee a problem or two with more advanced situations in validation and edit state management, so I would probably write a custom version of the Blazor InputText.

Upvotes: 1

Related Questions