3

I'm having trouble trying to write a form with time field using ASP.NET MVC 4.

Model:

class Abcde {
    [DataType(DataType.Time)]
    public DateTime ATime { get; set; }
}

View.cshtml

...
@Html.EditorFor(m => m.ATime)
@Html.ValidationMessageFor(m => m.ATime)

The validation always failed when I tried to input a time (hh:nn:ss), and said it was not in the corrent format, so i have to input a date instead. My Question is should I change the type to TimeSpan? Or is there any other way?

4

4 回答 4

9
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")]
public DateTime Time { get; set; }`

试试这个,你可以按照你希望它为你工作的方式格式化 DataFormatString,我现在在一个项目中使用它,它对我有用。

于 2013-07-10T08:06:37.077 回答
4

实际上,这对我有用。

[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }
于 2016-10-22T23:40:49.400 回答
0
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Time { get; set; }

这段代码是正确的。但它仅在您使用EditorFor而不是TextBoxFor.

于 2019-07-03T11:49:21.143 回答
-2

利用:

[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm:ss}")]
public DateTime FieldTime{ get; set; }

您需要将您的日期验证与此注释在内部工作的格式相匹配。因此,添加传递字符串模式的 ApplyFormat 即可获得它。

于 2019-07-17T20:16:52.453 回答