[英]Remove seconds from TimeSpan EditorFor
I am creating a view containing a form in ASP.NET MVC3 for a model containing time spans.我正在为包含时间跨度的 model 创建一个包含 ASP.NET MVC3 表单的视图。 I was wondering if there is a way that I can prevent the text box that is rendered from showing the seconds part?我想知道是否有一种方法可以防止呈现的文本框显示秒部分? So that instead of 12:30:00
, I would get 12:30
?所以我会得到12:30
而不是12:30:00
?
Here is what I have in the model and view:这是我在 model 中的内容并查看:
//model
[Required]
[DataType(DataType.Time)]
public TimeSpan Start { get; set; }
//view
<div class="editor-field">
@Html.EditorFor(model => model.Start)
@Html.ValidationMessageFor(model => model.Start)
</div>
Any advice would be much appreciated.任何建议将不胜感激。
You could use the [DisplayFormat]
attribute:您可以使用[DisplayFormat]
属性:
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan Start { get; set; }
The answer of Darin works but the validation still not work like I would expect. Darin 的答案有效,但验证仍然不像我预期的那样有效。 I added a custom validation.我添加了自定义验证。 That custom validation is doing a regular expression without a regular expression attribute.该自定义验证正在执行没有正则表达式属性的正则表达式。 This is done otherwise you can't post times like 14:30 because the regular expression will stop it or the TimeSpan object will stop it because it expects a TimeSpan like 00:00:00.这是完成的,否则您不能发布像 14:30 这样的时间,因为正则表达式会停止它,或者 TimeSpan object 会停止它,因为它需要像 00:00:00 这样的 TimeSpan。
So I created this validation for MVC 5 with Entity Framework 6 in Visual Studio 2013 Update 4.因此,我在 Visual Studio 2013 Update 4 中使用实体框架 6 为 MVC 5 创建了此验证。
public class Training : IValidatableObject
{
private const string Time = @"^(?:[01][0-9]|2[0-3]):[0-5][0-9]:00$";
public int Id { get; set; }
[Display(Name = "Starttime")]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan StartTime { get; set; }
[Display(Name = "Endtime")]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan EndTime { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
Regex timeRegex = new Regex(Time);
if (!timeRegex.IsMatch(StartTime.ToString()))
{
results.Add(new ValidationResult("Starttime is not a valid time hh:mm", new[] { "StartTime" }));
}
if (!timeRegex.IsMatch(EndTime.ToString()))
{
results.Add(new ValidationResult("Endtime is not a valid time hh:mm", new[] { "EndTime" }));
}
return results;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.