How to display a TimeSpan in MVC Razor

后端 未结 3 995
无人共我
无人共我 2021-01-20 12:54

So I have a duration in seconds of a video and I would like to display that duration in Razor.

Currently I am using

@TimeSpan.FromSeconds(item.Dura         


        
3条回答
  •  情书的邮戳
    2021-01-20 13:13

    John,

    Create your own display template. To do this, follow these steps:

    1. Create a folder called DisplayTemplates under Views/Shared
    2. Under that new folder, create a partial view called TimeSpan.cshtml
    3. Now, in your view, anytime you encounter a model property that is a timespan, it will automatically be rendered by the TimeSpan DisplayTemplate.
    4. Add a new get property to your model.

    Model edit (add the following):

    public TimeSpan MyTimeSpanProperty
    {
        get
        {
            return TimeSpan.FromSeconds(Duration);
        }
    }
    

    TimeSpan.cshtml

    @model TimeSpan
    @string.Format("{0}:{1}:{2}", Model.Hours, Model.Minutes, Model.Seconds)
    

    Invoked in your view as

    @Html.DisplayFor(m => m.MyTimeSpanProperty)
    

    This will display as 3:24:16 etc..

    That's all there is to it (tho it assumes that you'll pass in a property of type TimeSpan, so if possible, see if you can make that minor change to your model !! )

提交回复
热议问题