Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

Format timespan as TotalMilliseconds

I am writing a simple ASP.Net page, where I have several fields, one of them is for timeout. I want to display it as milliseconds (but still want to have a timespan instead of int/string). I am writing following code:

<input asp-for="Entry.Interval" asp-format="{0:fff}" type="text" class="form-control"> 

But here is a problem. This format is not working as expected. I expect TimeSpan.FromMinutes(2).ToString("fff") to return 120000, but it returns 000. It's obviosly becuase TimeSpan uses Milliseconds property, which is zero in this example, but I need TotalMilliseconds.

Is there some format which force to show entire TimeSpan in desired units? I really don't want to write an integer field and map it manually on this TimeSpan.

Upvotes: 4

Views: 1539

Answers (1)

slawekwin
slawekwin

Reputation: 6310

You could define another property only to be used in binding

class Entry
{
    public TimeSpan Interval { get; set; }
    public int IntervalMS
    {
        get { return (int)Interval.TotalMilliseconds; }
        set { Interval = TimeSpan.FromMilliseconds(value); }
    }
    //other stuff...
}

And then

<input asp-for="Entry.IntervalMs" type="text" class="form-control"> 

Upvotes: 4

Related Questions