【问题标题】:Required property not found in json在 json 中找不到必需的属性
【发布时间】:2017-01-29 11:47:12
【问题描述】:

我正在尝试在提交到服务器之前强制填写一个字段。为此,我使用 [Required] 数据注释进行模型验证。对于 string 数据类型,它可以按预期工作,但对于 double 则不行。

由于某种原因,它不适用于 double 类型的属性。 这是我为 model 提供的代码:

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; }
}

响应正文是 JSON 响应,对于已完成的必填字段均未包含以下内容:

{
 "Message":"The request is invalid.",
 "ModelState":
            {"product":["Required property 'UnitPrice' not found in JSON. Path '', line 1, position 33."],
             "product.Barcode":["The Barcode field is required."],
             "product.Name":["Please insert the product name!"]
            }
}

我不明白为什么 NameBarcode 可以正常工作,而 UnitPrice 不能正常工作。

编辑 1

如果我删除 [Required] 属性并将 UnitPrice 的输入放入 -1 我会收到适当的验证消息,那么为什么不适用于 必需的属性?

Edit 2:请求负载(也更新了ProductMetadata类):

{IsDelete: false, CategoryId: 1}
CategoryId: 1
IsDelete: false

感谢任何帮助!谢谢!

【问题讨论】:

  • 你能分享你的请求负载 - JSON吗?
  • @Paritosh 我已经编辑了问题

标签: json asp.net-mvc validation


【解决方案1】:

最快的决定是让 Unit Price 可以为空

[Range(0, 1000000)]
[Required(ErrorMessage="Please provide a unit price for the product!")]
public double? UnitPrice { get; set; }

问题是 json 中缺少字段 Unit Price 并且 JSON Formatter 尝试反序列化 double 并在执行 Required 之前收到异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多