如何让 MVC 模型 属性 到 return 日期而不是日期时间?
How to get MVC model property to return a Date instead of DateTime?
我的数据库有一个模型,它有一个 DateTime 属性。然而,这个 属性 确实是一个 Date。当客户端 sorting/filtering 时,额外的时间组件会导致问题。许多 tables/client 组件都有这个问题。
我希望我可以在模型级别修复此问题,并在通过以下修改访问时仅检索日期部分。
private DateTime invoiceDate;
[Required]
public DateTime InvoiceDate { get => invoiceDate.Date; set =>invoiceDate = value; }
但是,这似乎不起作用。这样的事情可能吗?
编辑:我发现 C# 允许对模型指定更具体的数据类型 - https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
即
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
但是,当我点击 API 时,我仍然获得完整的数据库信息
"InvoiceDate": "2019-06-14T00:00:00-07:00"
为什么 C# 不使用提供的额外规范来解决这个问题?
编辑:
我还发现 this helpful thread 建议向 属性 添加一个 JSON 转换器,但这也没有解决问题。时间还在发送中。
您可以使用 Bind
排除您的 属性
[Bind(Exclude="InvoiceDate")]
public class YourModel{
}
我最终通过修改 OData 请求使其工作。我必须编辑字符串以将 属性 包裹在 data(prop)
中,然后我必须编辑值以从 javascript 的 DateTime.ToString yyyy-MM-dd
中删除时间
我的数据库有一个模型,它有一个 DateTime 属性。然而,这个 属性 确实是一个 Date。当客户端 sorting/filtering 时,额外的时间组件会导致问题。许多 tables/client 组件都有这个问题。
我希望我可以在模型级别修复此问题,并在通过以下修改访问时仅检索日期部分。
private DateTime invoiceDate;
[Required]
public DateTime InvoiceDate { get => invoiceDate.Date; set =>invoiceDate = value; }
但是,这似乎不起作用。这样的事情可能吗?
编辑:我发现 C# 允许对模型指定更具体的数据类型 - https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
即
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
但是,当我点击 API 时,我仍然获得完整的数据库信息
"InvoiceDate": "2019-06-14T00:00:00-07:00"
为什么 C# 不使用提供的额外规范来解决这个问题?
编辑:
我还发现 this helpful thread 建议向 属性 添加一个 JSON 转换器,但这也没有解决问题。时间还在发送中。
您可以使用 Bind
排除您的 属性
[Bind(Exclude="InvoiceDate")]
public class YourModel{
}
我最终通过修改 OData 请求使其工作。我必须编辑字符串以将 属性 包裹在 data(prop)
中,然后我必须编辑值以从 javascript 的 DateTime.ToString yyyy-MM-dd