I have a summary page which is computing several average and total times from stored items in the database. All of the calculations work, but due to how the averages are computed the values are stored as a double representing the number of minutes. The goal here is to convert this to a HH:MM:SS format when displaying the averages and totals on the Razor Page.
I started here.
How to display a TimeSpan in MVC Razor
It seemed like bad practice to create a helper class for every single average and total I have to display, so I made the solution a bit more general with a method.
public string TSConvert(double minutes)
{
return TimeSpan.FromMinutes(minutes).ToString(@"hh\:mm\:ss");
}
So this works
<td>
@item.TSConvert(item.SalesAverageTime)
</td>
This does not
<td>
@Html.DisplayFor(modelItem => item.TSConvert(item.SalesTotalTime))
</td>
Specifically, I see the following error:
InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Is there a way to make this method play nicely with the DisplayFor? If not, is there a big impact in going around DisplayFor as I've done above?
Couple different things going on here:
The error is because you are not using DisplayFor to display an object propety. Instead use @Html.Raw:
Additionally instead of placing the convert method on your object I would recommend using a separate class (or even an extension method). For example:
Then call it like:
That way you can reuse it with another class if you need to.