How to display a TimeSpan in MVC Razor

后端 未结 3 958
无人共我
无人共我 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:07

    You should take advantage of DataAnnotations namespace and DisplayTemplates in ASP.NET MVC

    1. First mask your property with UIHint Attribute and set the template to VideoDuration in Models/YourVideoModel.cs

      [UIHint("VideoDuration")]
      public int Duration { get; set; }
      
    2. Add a display template to your project at Views/Shared/DisplayTemplates/VideoDuration.cshtml (you may need to add folder DisplayTemplates if it not present)

      @model int?
      @string.Format("{0:g}", TimeSpan.FromSeconds(Model))
      

    Then you can use it in your view like this:

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

提交回复
热议问题