【发布时间】:2021-08-09 20:32:47
【问题描述】:
当我通过按删除按钮清除InputNumber控件中的值,然后按tab按钮时,该值保持不变并且没有更新。
我绑定InputNumber控件的属性如下
[Required]
[RegularExpression(@"^\d+.\d{0,6}$", ErrorMessage = "The Price field cannot have more than 2 decimal places.")]
public decimal Price {get;set;}
我怎样才能使当我按下删除按钮时,Price 更新为 0?
我想让这发生的原因是当前的行为导致了一些问题。 这是一个例子:
-
在
Quantity属性的setter中,当Quantity被设置时,如果Quantity和Price不为0则设置Unit Price为Price除以Quantity -
将
Price设置为 100 -
按删除按钮删除
Price。 错误消息尖叫"The Price field is required.",但Price的值仍为100 -
将
Quantity设置为 10。Unit Price被错误地计算为 10。尽管在Price的<InputNumber>控件上显示的是空而不是 100。
我试过了:
-
在
<InputNumber>控件上使用@OnEmptied=> 也不更新Price的值 -
将
decimal变成decimal?这没有多大帮助,因为我仍然想验证是否输入了Price
任何建议将不胜感激!
完整代码如下(index.razor):
@page "/"
@using System.ComponentModel.DataAnnotations;
<EditForm Model="item">
<DataAnnotationsValidator></DataAnnotationsValidator>
<div>
<label>Quantity:</label>
<InputNumber @bind-Value="item.Quantity"></InputNumber>
<ValidationMessage For="@(()=>item.Quantity)"></ValidationMessage>
</div>
<div>
<label>Unit Price:</label>
<InputNumber @bind-Value="item.UnitPrice"></InputNumber>
<ValidationMessage For="@(()=>item.UnitPrice)"></ValidationMessage>
</div>
<div>
<label>Price:</label>
<InputNumber @bind-Value="item.Price"></InputNumber>
<ValidationMessage For="@(()=>item.Price)"></ValidationMessage>
</div>
</EditForm>
@code {
private Item item = new Item()
{
Price = 0,
Quantity = 0,
UnitPrice = 0
};
public class Item
{
private decimal _quantity;
[Required]
[RegularExpression(@"^\d+.\d{0,6}$", ErrorMessage = "The Qauntity field cannot have more than 6 decimal places.")]
public decimal Quantity
{
get => _quantity;
set
{
_quantity = Math.Abs(value);
if (_unitPrice == 0 && _quantity != 0 && _price != 0)
{
_unitPrice = decimal.Round(_price / _quantity, 6);
}
if (_quantity != 0 && _unitPrice != 0)
{
_price = decimal.Round(_quantity * _unitPrice, 2);
}
}
}
private decimal _unitPrice;
[Required]
[RegularExpression(@"^\d+.\d{0,6}$", ErrorMessage = "The Unit Price field cannot have more than 6 decimal places.")]
public decimal UnitPrice
{
get => _unitPrice;
set
{
_unitPrice = Math.Abs(value);
if (_quantity == 0 && _unitPrice != 0 && _price != 0)
{
_quantity = decimal.Round(_price / _unitPrice, 6);
}
if (_quantity != 0 && _unitPrice != 0)
{
_price = decimal.Round(_quantity * _unitPrice, 2);
}
}
}
private decimal _price;
[Required]
[RegularExpression(@"^\d+.\d{0,6}$", ErrorMessage = "The Price field cannot have more than 2 decimal places.")]
public decimal Price
{
get => _price;
set
{
_price = Math.Abs(value);
if (_quantity == 0 && _price != 0 && _unitPrice != 0)
{
_quantity = decimal.Round(_price / _unitPrice, 6);
}
if (_unitPrice == 0 && _price != 0 && _quantity != 0)
{
_unitPrice = decimal.Round(_price / _quantity, 6);
}
}
}
}
}
【问题讨论】:
-
你能分享
InputNumber和Quantity的代码吗? -
@ConnorLow 当然!我已经添加了完整的代码。
-
“按下删除按钮”是指您正在清除输入内容,还是与
Delete键相关的键盘事件您没有泄露? -
另外,
Price的正则表达式应该是^\d+.\d{0,2}$吗?否则您的错误消息不匹配。
标签: html asp.net-core blazor