Franky
Franky

Reputation: 1574

Blazor binding variable issue

In my Blazor project, I have a simple input textbox where I want to bind to a product price value. The price is initially calculated as:

PackageObject.Price = PackageObject.PackageProducts.Sum(x => x.Product.Price * x.Qty);

Then I bind the variable to the textbox:

<input class="form-control" type="text" @bind="@PackageObject.Price" placeholder="Package Price" />

The goal here is to set the initial value as the calculated value but then allow user to change it using the textbox.

However, I am not able to change the value at all! Say the calculated price is 800 and I want to change it to whatever else, it immediately change the value back to 800!

I assume because of the calculation, it's tied to the objects. Without changing the objects' own underlying pricing, this calculated price will always reflect what the calculation does. But I've then change it to use a variable like;

var price = PackageObject.PackageProducts.Sum(x => x.Product.Price * x.Qty);

I then bind the variable @price to the textbox, same thing. I couldn't figure out a way by setting the textbox with my initially calculated value and then let user change it as needed.

Help please.

Thanks!

Frank

Upvotes: 1

Views: 378

Answers (2)

enet
enet

Reputation: 45586

I've tried to reproduce your issue, but without complete repo of your code I'm not able to determine what is wrong, or accept your conclusion. Below is a code snippet that works well, and update the PackageObject.Price field as expected. Note that the calculation takes place in the OnInitialized life-cycle method which occurs only once, and perhaps this is why my sample works without issue. But I'm not entirely sure of that.

Usage

 <input class="form-control" type="text" @bind="@_PackageObject.TotalPrice" 
   placeholder="Package Price" />
 <input type="button" @onclick="@(() => { })" value="Refresh page"/>

 <p>@_PackageObject.TotalPrice</p>

 @code
 {

    PackageObject _PackageObject = new PackageObject();

   protected override void OnInitialized()
  {
    _PackageObject.ID = 1;
    _PackageObject.TotalPrice = _PackageObject.PackageProducts.Sum(p => 
     p.Price * p.Qty);

    Console.WriteLine(_PackageObject.TotalPrice);

  }



 public class PackageObject
 {
    public int ID { get; set; }
    public int TotalPrice { get; set; }
    public List<Product> PackageProducts { get; set; } =
               Enumerable.Range(1, 5).
     Select(i => new Product { ID = i, Price = 50, Qty=10 }).ToList();
 }



 public class Product
 {
    public int ID { get; set; }
    public int Price { get; set; }
    public int Qty { get; set; }
 }
} 

Upvotes: 1

tbdrz
tbdrz

Reputation: 2190

Set the value in the OnInitialized or OnInitializedAsync method:

protected override void OnInitialized()
{
    PackageObject.Price = PackageObject.PackageProducts.Sum(x => x.Product.Price * x.Qty);
}

Upvotes: 2

Related Questions