I have DisplayFor showing a TimeSpan-value (Duration) in this format: 35.04:08:43.2470000 (dd.HH:mm:ss.fffffff).
My goal is a human-readable string "HH:mm" so I followed How to display a TimeSpan in MVC Razor and tried making a DisplayTemplate in ~views/Shared/TimeSpanTemplate.cshtml:
@model TimeSpan
@{
TimeSpan initialValue = Model;
}
@string.Format("{0}:{1}", (initialValue.Days * 24) + initialValue.Hours, initialValue.Minutes)
@Scripts.Render("~/bundles/bootstrap")
This is my model:
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[DisplayName("Varighed")]
public virtual TimeSpan? Duration
{
get {
return SolvedDate.HasValue ? (TimeSpan?)SolvedDate.Value.Subtract(ReportedDate) : null; }
}
This is my view:
<td>
@Html.DisplayFor(modelItem => item.Ticket.Duration)
</td>
I get this compile formatexception error:
Input string was not in a correct format. --> "@Html.DisplayFor(modelItem => item.Ticket.Duration)"
System.FormatException was unhandled by user code
HResult=-2146233033 Message=Input string was not in a correct format. Source=mscorlib
I have successfully created DateTime-templates for EditViews, but I cant seem to get around this problem on DisplayFor with TimeSpan-types.
I dont have the faintest idea what I am doing, so any clues are appreciated! :) Thanks in advance!
This is not a direct answer to solve this problem, but I think it would be better to use the Humanizer library.
You would be able to do the following:
SolvedDate.Humanize();
See here: https://github.com/Humanizr/Humanizer#humanize-timespan
Your Timespan is nullable so try:
<td>
@Html.Label("MyTimeSpan", Model.Ticket.Duration != null ? Model.Ticket.Duration.Value : string.Empty)
</td>
After reading How can I String.Format a TimeSpan object with a custom format in .NET?
I managed to solve this myself, by outcommenting my TimeSpanTemplate, and simply edit this line in my model from: [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
to
[DisplayFormat(DataFormatString = "{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ApplyFormatInEditMode = true)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.