Home How to format Date, Time, Number in ASP.NET Core 2.0, RAZOR Tag Helpers
Reply: 0

How to format Date, Time, Number in ASP.NET Core 2.0, RAZOR Tag Helpers

user2873 Published in April 22, 2018, 12:48 am

I'm facing problems trying to format DateTime and Numbers in ASP.NET MVC Core 2.0 App using Razor Tag Helpers.

Following the good practices I would like to specify data format at the data model related to the form view.

My Model

public class OrderFormModel
    public bool IsEdit { get; set; }

    [Display(Name = "Order Time: ")]
    public DateTime ORDER_LOCAL_TIME { get; set; }

    [Display(Name = "Order Qty (K): ")]
    public int QUANTITY_K { get; set; }

The view:

        <div class="form-group col-md-9">
            <label asp-for="ORDER_LOCAL_TIME"></label>
            <input asp-for="ORDER_LOCAL_TIME" class="form-control" />
            <span asp-validation-for="ORDER_LOCAL_TIME" class="text-danger"></span>
        <div class="form-group col-md-6">
            <label asp-for="QUANTITY_K"></label>
            <input asp-for="QUANTITY_K" min="1" class="form-control" style="text-align:right" />
            <span asp-validation-for="QUANTITY_K" class="text-danger"></span>

The desired formats are

12/12/2017 12:23 (can be separated in to two fields as workaround)

1 000.145

I've been trying a lot of options but none of them works. For the number input I would like when the user enters the value and leaves the input, the format to be applied.

I've been trying:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm}")] (not applied at all)

[DisplayFormat(DataFormatString = "{0:N3}")] (not applied at all)

[DataType(DataType.Time)] (applied but seconds, milliseconds and AM/PM present)

[DataType(DataType.Date)] (works for date only field)

Your help is highly appreciated. Thanks.


As Stephen Muecke noted [DisplayFormat] applies the format when the page is first rendered. Agree, thanks. I have initial values for ORDER_LOCAL_TIME and QUANTITY_K properties. DateTime = now for ORDER_LOCAL_TIME and 1000 for QUANTITY_K.

So for example on New Order Action I would like Form View to show formatted initial values for Date with Time (mm:ss only) and Quantity (with thousand separator). The problem is I cant achieve that.

As Stephen Muecke notices format applied when your in the browser and the user edits a value and leaves the input is another story. If I use Java Script function connected to the OnChange event of the QUANTITY input, I can format and try to return formatted number as text to the input. But in this case: << jquery.js:7592 The specified value "3 000" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)? >>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303108 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO