20

我有一个包含一些时间选择器的 MVC 页面。这些作为 nullable 存储在模型中的对象列表中TimeSpan。问题是我在输入字段中打印了以秒为单位的时间跨度。有什么方法可以格式化这些模型属性,以便我以其他方式打印时间跨度(例如7:00,而不是07:00:00)?不用说,我的“建议”[DisplayFormat...]没有奏效。至少不是我希望的那样。

输入字段定义如下:

@Html.TextBoxFor(x => x.Shifts[i].Start)

模型的相关部分如下所示:

public class Workshift
{
    [DisplayFormat(Something here perhaps?)]
    public TimeSpan? Start { get; set; }
    public TimeSpan? End { get; set; }
    public TimeSpan? Pause { get; set; }
}

public class TimeRegistrationViewModel
{
    public List<Workshift> Shifts { get; set; }

    ...
}

一如既往地欣赏它!

4

1 回答 1

35
[DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
public TimeSpan? Start { get; set; }

[DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
public TimeSpan? End { get; set; }

[DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
public TimeSpan? Pause { get; set; }

但请记住,for 的主要目的TimeSpan是表示测量的持续时间,而不是一天中的某个时间。这意味着TimeSpan值可以超过 24 小时。它们也可以是负数,表示在时间线上向后移动。

将它们用作一天中的时间是可以接受的,实际上是由框架本身完成的(例如,DateTime.TimeOfDay)。但是当以这种方式使用时,您应该仔细验证用户输入。如果您仅依赖数据类型,则用户可能能够输入有效时间跨度的值,但不是有效的白天时间。例如,表示过去1 天 22 小时 33 分钟 44 秒-1.22:33:44的有效值。TimeSpan

Time如果 .Net 有本机类型会容易得多,但它没有更新: CoreFXLab中的包中现在有一个原生TimeOfDay类型。System.Time

此外,该TextBoxFor方法不会拾取数据注释。您可以直接将格式字符串指定为参数,如下所示:

@Html.TextBoxFor(x => x.Shifts[i].Start, "{0:hh\\:mm}")

或者你可以切换到EditorFor这样的:

@Html.EditorFor(x => x.Shifts[i].Start)
于 2013-07-14T04:31:02.693 回答