需要解决的问题:
- 从 MVC 应用程序获取时间和日期
我的具体问题:我有一个 parking 管理应用程序。由于可以提前预订 parking 位,因此我需要知道 parking 开始时间和日期。对于我的模型,我使用了 DateTime,因为 MSDN 将其宣传为全功能时间和日期数据类型:
The .NET Framework DateTime class provides a full-featured interface for writing programs that deal with time.
我的研究:我搜索了此类问题的答案或典型解决方案(最佳实践),几乎所有我得到的是:
- 全局化的问题
- 时区问题
- 不同的日期格式
但没有考虑如何使用 MVC 应用程序方便地获取日期和时间。
我找到的最接近的答案是 Scott Hanselman 2009 年的解决方案 - http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
人们倾向于使用的其他解决方案是不同的 jQuery 插件。
对我来说,这些解决方案似乎略微过度设计。因为我不知道还有什么地方可以问,也不知道这些是否是唯一的解决方案 - 我的问题是:
- 我有哪些使用 MVC 获取时间和日期的选项 - 最佳实践?
在我的模型中,我使用:
[DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:HH:mm dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ParkingStartTime { get; set; }
在我看来我使用:
<div class="editor-label">
@Html.LabelFor(vm => vm.newCarOnParkingSpot.ParkingStartTime)
</div>
<div class="editor-field">
@Html.EditorFor(vm => vm.newCarOnParkingSpot.ParkingStartTime)
@Html.ValidationMessageFor(vm => vm.newCarOnParkingSpot.ParkingStartTime)
</div>
此解决方案为我提供了一个 HTML5 日期选择器,但没有时间插入选项:http://i.stack.imgur.com/fGPTV.png
这是我的第一个问题,所以如果我对这个问题有误,请多多包涵。
最佳答案
正如@SLC 建议的那样,我使用了 jQuery。我选择了 jQuery DateTimePicker http://xdsoft.net/jqplugins/datetimepicker/
根据 SLC:
There's no best practice for this, the jquery date picker would work fine and is pretty simple
他是对的。我在 7 分钟内解决了我的问题。
我所做的只是:
- 将 jQuery DateTimePicker 文件添加到我的项目(来自上面的站点)
- 按照该站点上提供的说明进行操作(向 cshtml 文件添加了 2 个脚本和 1 个 css 文件,向所需的输入字段添加了一个 id,并在之前添加的 id 上调用了 jQuery 函数 - 瞧!)
- 将数据保存到 DateTime 数据类型的数据库花费 0 分钟
我觉得一个需要改进的地方是我的 jQuery 函数调用。还有比这更好的方法吗?:
<script type="text/javascript">
$(document).ready(function () {
jQuery('#datetimepicker').datetimepicker();
});
关于c# - 使用 MVC 获取 DateTime 类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31542330/