在json中找不到必需的属性
在提交到服务器之前,我试图将字段设置为必填字段。为此,我使用了[Required]数据注释进行模型验证。对于字符串数据类型,它按预期工作,但对于双精度则不起作用 出于某种原因,它不适用于double类型属性。 以下是我为型号编写的代码:在json中找不到必需的属性,json,asp.net-mvc,validation,Json,Asp.net Mvc,Validation,在提交到服务器之前,我试图将字段设置为必填字段。为此,我使用了[Required]数据注释进行模型验证。对于字符串数据类型,它按预期工作,但对于双精度则不起作用 出于某种原因,它不适用于double类型属性。 以下是我为型号编写的代码: public class ProductMetadata { [Required] public string Barcode { get; set; } [StringLength(50)] [Required(AllowEm
public class ProductMetadata
{
[Required]
public string Barcode { get; set; }
[StringLength(50)]
[Required(AllowEmptyStrings = false, ErrorMessage="Please insert the product name!")]
public string Name { get; set; }
[Range(0, 5000)]
public double ShippingCostPerUnit { get; set; }
[Range(0, 10000)]
public int QuantityForFreeShipping { get; set; }
public Nullable<int> CategoryId { get; set; }
public bool IsDeleted { get; set; }
[Range(0, 1000000)]
[Required(ErrorMessage="Please provide a unit price for the product!")]
public double UnitPrice { get; set; }
}
我不明白为什么对名称和条形码有效,而对单价无效
编辑1:
public class ProductMetadata
{
[Required]
public string Barcode { get; set; }
[StringLength(50)]
[Required(AllowEmptyStrings = false, ErrorMessage="Please insert the product name!")]
public string Name { get; set; }
[Range(0, 5000)]
public double ShippingCostPerUnit { get; set; }
[Range(0, 10000)]
public int QuantityForFreeShipping { get; set; }
public Nullable<int> CategoryId { get; set; }
public bool IsDeleted { get; set; }
[Range(0, 1000000)]
[Required(ErrorMessage="Please provide a unit price for the product!")]
public double UnitPrice { get; set; }
}
如果我删除了[Required]属性,并输入了单价-1,我会收到相应的验证消息,那么为什么不使用Required属性呢
编辑2:请求有效负载(还更新了产品元数据类):
感谢您的帮助!谢谢 最快的决定是使单价为零
[Range(0, 1000000)]
[Required(ErrorMessage="Please provide a unit price for the product!")]
public double? UnitPrice { get; set; }
问题是json中缺少字段单价,json格式化程序尝试反序列化double并在执行Required之前接收异常。您可以共享您的请求有效负载-json吗?@Paritosh我已编辑了该问题
[Range(0, 1000000)]
[Required(ErrorMessage="Please provide a unit price for the product!")]
public double? UnitPrice { get; set; }