View MVC C# 中的格式异常

Format Exception in View MVC C#

以下是摘自我的视图模型的片段:

[Display(Name = "Time")]
    [Required(ErrorMessage = "Is required field. Format hh:mm (24 hour time)")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
    public Nullable<System.TimeSpan> EventPerformance_Time { get; set; }

这是我的 View.cshtml:

<div class="form-group">
            @Html.LabelFor(model => model.EventPerformance_Time, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EventPerformance_Time, "{0:HH:mm}", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EventPerformance_Time, "", new { @class = "text-danger" })
            </div>
        </div>

当我 运行 项目时,我不断收到以下错误:

FormatException: Input string was not in a correct format.

在@Html.EditorFor行.....等等

我尝试了很多不同的 'solutions' 和 none 都有效,但我很困惑哪里出了问题,因为在另一个视图模型中它工作得很好!

有什么帮助吗?非常感激。

我很想看看您的示例在何处起作用。您使用的是什么版本的 MVC?在EditExtension.EditorFor or EditorExtensions.EditorFor Methods documentation I don't see a method signature that supports what you are dong. Can you maybe do something along these lines Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?

此格式有效:“{0:hh:mm:ss}”

https://msdn.microsoft.com/en-us/library/ee372287%28v=vs.110%29.aspx

public class Test
{
    [Display(Name = "Time")]
    [Required(ErrorMessage = "Is required field. Format hh:mm (24 hour time)")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm\:ss}")]
    public Nullable<System.TimeSpan> EventPerformance_Time { get; set; }
}


<div>
@Html.LabelFor(m => m.EventPerformance_Time)
<div>
    @Html.EditorFor(m => m.EventPerformance_Time)
</div>