ModelState.IsValid 是错误的,但应该是正确的

ModelState.IsValid is false but should be true

我有一个 ASP.NET MVC 应用程序 AJAX 正在更新。每个实体的 CRUD 操作都正常工作,但创建 "Receipt" 除外。当控制器点击 ModelState.IsValid 时会出现问题,这会转化为 false,而实际上它应该是 true。一步步调试了那么多次,该为真却总是假

我正在使用 Entity Framework 进行实体操作,这是从 SQL 服务器数据库生成的代码:

public partial class Receipt
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Receipt()
    {
        this.Receipts1 = new HashSet<Receipt>();
        this.Seminars = new HashSet<Seminar>();
    }

    public int Id { get; set; }
    public System.DateTime IssueDate { get; set; }
    public Nullable<System.DateTime> DeliveryDate { get; set; }
    public Nullable<System.DateTime> PaymentDue { get; set; }
    public Nullable<short> CompanyId { get; set; }
    public Nullable<int> Number { get; set; }
    public Nullable<int> ClosedReceiptId { get; set; }
    public Nullable<decimal> ReturnedAmount { get; set; }
    public Nullable<short> ReturnTypeId { get; set; }

    public virtual Company Company { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Receipt> Receipts1 { get; set; }
    public virtual Receipt Receipt1 { get; set; }
    public virtual ReturnType ReturnType { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Seminar> Seminars { get; set; }
}

最重要的是我有 ReceiptMetadata 注释和 [Required] 字段:

[MetadataType(typeof(ReceiptMetadata))]
public partial class Receipt
{
}

public class ReceiptMetadata
{
    [Required]
    public int Number { get; set; }

    [Required]
    [DisplayName("Issue Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:G}")]
    public DateTime IssueDate { get; set; }

    [Required]
    [DisplayName("Payment Due")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
    public DateTime? PaymentDue { get; set; }

    [DisplayName("Return amount")]
    [DisplayFormat(DataFormatString = "{0:c}")]
    public Nullable<decimal> ReturnedAmount { get; set; }
}

而我在控制器中的Create函数如下:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "Id,IssueDate,DeliveryDate,PaymentDue,CompanyId,Number")]Receipt receipt, int? seminarId)
{
    if (seminarId == null)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Message = "ID is required" });
    }

    Seminar seminar = db.Seminars.Find(seminarId);

    if (seminar == null)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Message = "Seminar doesn't exist" });
    }

    int receiptNumber = db.Receipts.Where(r => r.CompanyId == receipt.CompanyId && r.ClosedReceiptId == null && r.IssueDate.Year == DateTime.Now.Year).Count() + 1;
    receipt.Number = receiptNumber;
    receipt.IssueDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, TimeZoneInfo.Local.Id, "Central European Standard Time");

    if (ModelState.IsValid)
    {
        try
        {
            db.Receipts.Add(receipt);
            db.SaveChanges();

            seminar.ReceiptId = receipt.Id;
            db.Entry(seminar).State = EntityState.Modified;

            db.SaveChanges();

            GeneratePDF(receipt.Id, receipt.ReceiptNumber, receipt.CompanyId.ToString());
            return Json(new { receipt.Id, receipt.PDFLink, Action = "Create", Message = "Receipt successfully added! -> " }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { Message = ex.Message });
        }
    }

    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
    List<string> errorMessages = new List<string>();

    foreach (ModelError error in allErrors)
    {
        errorMessages.Add(error.ErrorMessage);
    }

    return Json(new { Message = errorMessages });
}

我得到的错误是

The Number field is required.

当字段 Number 显然填写为:

receipt.Number = receiptNumber;

IsValid 前几行。

有人可以帮忙吗?

编辑:这是调试的截图,模型状态键完全错误:

输入您的操作时,ModelState 已经被评估(并且无效),设置 "Number" 属性 将不会再次评估模型。设置 属性 后,您可能必须通过编写以下内容手动将其从模型错误中删除:

ModelState.Remove("Number");