Validation 表单验证-字段X必须是数字

Validation 表单验证-字段X必须是数字,validation,asp.net-core,Validation,Asp.net Core,在我的viewmodel中使用十进制字段时,asp.net core的表单验证出现问题,其中输入的值接收到一个带逗号的数字,但在提交时不允许 视图模型: public class MyViewModel { public decimal Price { get; set; } } <div class="form-group row"> <label asp-for="Price" req-asterisk="true" class="col-md-3 col

在我的viewmodel中使用十进制字段时,asp.net core的表单验证出现问题,其中输入的值接收到一个带逗号的数字,但在提交时不允许

视图模型:

public class MyViewModel
{
    public decimal Price { get; set; }
}
<div class="form-group row">
    <label asp-for="Price" req-asterisk="true" class="col-md-3 col-lg-2 col-form-label"></label>
    <div class="col-md-9 col-lg-10">
         <input asp-for="Price" class="form-control" rows="4" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
</div>
剃须刀页面:

public class MyViewModel
{
    public decimal Price { get; set; }
}
<div class="form-group row">
    <label asp-for="Price" req-asterisk="true" class="col-md-3 col-lg-2 col-form-label"></label>
    <div class="col-md-9 col-lg-10">
         <input asp-for="Price" class="form-control" rows="4" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
</div>


因此,例如,如果Price属性值为4000,输入值为4000,00,如果我单击submit,它会显示“字段价格必须是一个数字。”

考虑到您的
Price
字段需要包含该值,您将需要使用字符串来访问您的值。下面是一个示例,说明如何使用带有一些内存节省选项的字符串属性:

public class MyViewModel
{

    private string _priceDisplay;
    [DataType(DataType.Currency)]
    public string PriceDisplay {
        get => _priceDisplay ?? _price.ToString();
        set => _priceDisplay = value;
    }

    private decimal? _price;
    public decimal Price
    {
        get => _price ?? decimal.Parse(PriceDisplay);
        set => _price = value;
    }


}

您现在可以将您的输入映射到
PriceDisplay

尝试了这一点,但它只适用于客户端。您需要的不仅仅是验证。您需要在模型中将字符串转换为十进制,然后进行验证。