Asp.net

首次使用程式碼時允許模型中為空

  • January 3, 2022

我有一個這樣的模型:

public class EquipmentEmployee
{
   public int EquipmentEmployeeID { get; set; }

   public int EmployeeID { get; set; }
   public Employee Employee { get; set; }

   public int EquipmentID { get; set; }
   public Equipment Equipment { get; set; }

   public int RequisitionID { get; set; }
   public Requisition Requisition { get; set; }

   public DateTime From { get; set; }

   public DateTime To { get; set; }

   public string Comment { get; set; }

}

我使用 Mvc 腳手架來創建我的控制器、儲存庫和視圖。在創建視圖中我無法發布,因為我沒有“to”和“RequisitionID”的值。我沒有添加

$$ Required $$給他們。這可能嗎?要 POST 並讓這兩個為空?

您應該使用可為空的類型聲明可選欄位

public int? RequisitionID { get; set; }

要接受空值,您可以使用以下解決方案。

public int? RequisitionID { get; set; }

引用自:https://stackoverflow.com/questions/17421576