繁体   English   中英

格式化时间跨度-MVC C#Razor DisplayFor

[英]Formatting TimeSpan - MVC C# Razor DisplayFor

我有DisplayFor以以下格式显示TimeSpan值(持续时间):35.04:08:43.2470000(dd.HH:mm:ss.fffffff)。

我的目标是人类可读的字符串“ HH:mm”,因此我遵循了如何在MVC Razor中显示TimeSpan,并尝试在〜views / Shared / TimeSpanTemplate.cshtml中制作DisplayTemplate:

@model TimeSpan
@{
    TimeSpan initialValue = Model;
}
@string.Format("{0}:{1}", (initialValue.Days * 24) + initialValue.Hours, initialValue.Minutes)

@Scripts.Render("~/bundles/bootstrap")

这是我的模型:

[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[DisplayName("Varighed")]
public virtual TimeSpan? Duration
{
   get {
      return SolvedDate.HasValue ? (TimeSpan?)SolvedDate.Value.Subtract(ReportedDate) : null;        }
}

这是我的看法:

<td>
    @Html.DisplayFor(modelItem => item.Ticket.Duration)
</td>

我收到此编译formatexception错误:

输入的字符串格式不正确。 ->“ @ Html.DisplayFor(modelItem => item.Ticket.Duration)”

用户代码未处理System.FormatException
HResult = -2146233033消息=输入字符串的格式不正确。 来源= mscorlib

我已经成功地为EditViews创建了DateTime模板,但是我似乎无法在具有TimeSpan类型的DisplayFor上解决此问题。

我不知道我在做什么,所以任何线索都值得赞赏! :) 提前致谢!

这不是解决此问题的直接答案,但我认为使用Humanizer库会更好。

您将可以执行以下操作:

SolvedDate.Humanize();

看到这里: https : //github.com/Humanizr/Humanizer#humanize-timespan

您的时间跨度可以为空,因此请尝试:

<td>
    @Html.Label("MyTimeSpan", Model.Ticket.Duration != null ? Model.Ticket.Duration.Value : string.Empty)
</td>

阅读完后如何在.NET中使用自定义格式对TimeSpan对象进行String.Format格式化?

我设法解决了自己的问题,方法是对我的TimeSpanTemplate进行了注释,然后只需在模型中通过以下方式编辑此行: [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]

[DisplayFormat(DataFormatString = "{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ApplyFormatInEditMode = true)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM