从TimeSpan的EditorFor中删除秒数

13

我正在为一个包含时间跨度的模型创建ASP.NET MVC3中的视图,其中包含一个表单。我想知道是否有一种方法可以防止呈现的文本框显示秒钟部分?这样,我将获得12:30而不是12:30:00

以下是我的模型和视图内容:

//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>

非常感谢任何建议。

2个回答

27
你可以使用 [DisplayFormat] 属性:
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan Start { get; set; }

好的,这是我所遵循的相同解决方案,但不起作用!@Tom: 你在工作吗? - Alberto Rubini
1
@Alberto Rubini,你可能漏掉了什么。当你的问题描述是“但不起作用”时,这很难说清楚。 - Darin Dimitrov
在我的视图中,我的EditorFor控件的值是12:30:00,但我期望的是12:30。我尝试使用@"0:HH:mm"、@"0:hh:mm",但都不起作用!唯一的区别是我的属性是TimeSpan?(可空)。 - Alberto Rubini
@Alberto Rubini,你是在使用EditorFor辅助程序还是在编辑器模板中使用了TextBoxFor辅助程序? - Darin Dimitrov
正如Alberto所发现的那样,这在所有浏览器上都不起作用。它会在IE中显示格式,但在Chrome中被忽略。 - RobCroll
我使用@Html.EditorFor(model => model.Start),但这会生成一个运行时错误:“传递到字典中的模型项的类型为'System.TimeSpan',但此字典需要类型为'System.Nullable`1[System.DateTime]'的模型项。” 有任何想法为什么会出现这种情况? - ChrisFox

0

Darin的答案有效,但验证仍然不像我期望的那样工作。我添加了自定义验证。该自定义验证执行一个没有正则表达式属性的正则表达式。这样做是因为否则您无法发布类似于14:30的时间,因为正则表达式将停止它或TimeSpan对象将停止它,因为它期望类似于00:00:00的TimeSpan。

因此,我在Visual Studio 2013 Update 4中使用Entity Framework 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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接