Search code examples
c#razorblazorrazor-pagesblazor-webassembly

Binding Type double values in InputText of Blazor app Razor page


I am using InputText for almost all the attributes. Some of the attributes are of type Double. When I bind the double value in InputText its giving me error. How can i resolve this? I dont want to use InputNumber.

 <div class="form-group col">
 <label title="The quantity ">Quantity</label>
 <i class="fa fa-info-circle" style="color:dimgrey" title="The quantity"> 
 </i>
 <InputText @bind-Value="@trade.qty" class="form-control" />
 <ValidationMessage For="@(() => trade.qty)" />
 </div>

I am getting error at @trade.qty in <InputText @bind-Value="@trade.qty" class="form-control" /> as its a double value.

Model:

 public Double qty { get; set; }

I tried something like <InputText @bind-Value="@trade.qty.ToString()" class="form-control" /> It didnt't work.


Solution

  • I am not sure why you want that functionality, but what about creating support string property and converting the number inside?

    class MyModel
    {
        public Double qty { get; set; }
        public string qtyString{
          get=>qty.ToString();
          set{
            if(Double.TryParse(value, out double val))
            qty = val;
             }
          }
    }
    
    <InputText @bind-Value="@mod.qtyString"/>
    

    Working solution.