aspnet razor pages form local-datetime not working with NodaTime LocalDateTime

I have a form with an input of type local-datetime that is expecting a Date and a Time with the following format : yyyy-MM-ddTHH:mm

By default NodaTime LocalDateTime format is yyyy-MM-ddTHH:mm:ss and I need to strip the seconds from it.

Here is a sample razor pages app :

Project.csproj

<ItemGroup>
  <PackageReference Include="JetBrains.Annotations" Version="2024.2.0" />
  <PackageReference Include="NodaTime" Version="3.1.12" />
</ItemGroup>

CustomLocalDateTimeConverter.cs

// TypeConverterBase is coming from
// https://github.com/nodatime/nodatime/blob/main/src/NodaTime/Text/TypeConverterBase.cs
public class CustomLocalDateTimeConverter : TypeConverterBase<LocalDateTime>
{
    public CustomLocalDateTimeConverter()
      : base(LocalDateTimePattern.CreateWithInvariantCulture("uuuu-MM-dd'T'HH:mm")) { }
}

Program.cs

TypeDescriptor.AddAttributes(typeof(LocalDateTime),
    new TypeConverterAttribute(typeof(CustomLocalDateTimeConverter)));

Index.cs

public class IndexModel : PageModel
{
    [BindProperty]
    public LocalDateTime Local { get; set; } = new LocalDateTime(2024, 09, 11, 12, 12);
    
    public void OnPost()
    {
            
    }
}

Index.cs.cshtml

<form method="post">
    <input asp-for="Local" type="datetime-local" />
    <button type="submit">Send</button>
</form>

With this in place, if you select a value from the local-datetime input and send the form back to the server, the LocalDateTime will be parsed with the CustomLocalDateTimeConverter.

But when you load the page, the asp-for tag helper is rendering the date like this instead of showing the default date from Index.cshtml.cs:

And the generated html code is

<form method="post">
    <input type="text"
           data-val="true"
           data-val-required="The Local field is required."
           id="Local"
           name="Local"
           value="11/09/2024 12:12:00">
    <button type="submit">Send</button>
    <input name="__RequestVerificationToken" type="hidden" value="...">
</form>

The value attribute is not respecting the format, it looks like ToString() was used instead of our CustomLocalDateTimeConverter

7

This may or may not be the best way of doing it, but it’s fairly simple to specify the format used in an <input> element, using the Format property:

<input asp-for="Local" type="datetime-local" asp-format="{0:uuuu-MM-dd'T'HH:mm}" />

Note that I expect this will still use “the current culture” instead of an invariant culture pattern, which is definitely not ideal, but is unlikely to make any difference with the above pattern. (The LocalDateTime “knows” its own calendar system, so it’s not going to affect that, for example.)

You may well still need the answers from the earlier version of the question (e.g. specifying a [TypeConverter] attribute on the property) in order to make sure that the value is then parsed correctly on submission.

1

In an ASP.Net Core way you could try custom Model Binder.

ModelBinder

public class TimeModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

        var valueAsString = value.FirstValue;

        if (LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm").Parse(valueAsString).TryGetValue(LocalDateTime.MinIsoValue, out var localDateTime))
        {
            bindingContext.Result = ModelBindingResult.Success(localDateTime);
        }
        else
        {
            //...
        }

        return Task.CompletedTask;
    }
}

ModelBinderProvider

public class TimeModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        var modelType = context.Metadata.ModelType;

        if (modelType == typeof(LocalDateTime) || modelType == typeof(LocalDateTime?))
        {
            return new BinderTypeModelBinder(typeof(TimeModelBinder));
        }

        return null;
    }
}

Register service

builder.Services.AddRazorPages()
    .AddJsonOptions(o =>
        o.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb))
    .AddMvcOptions(options =>
    {
        options.ModelBinderProviders.Insert(0, new TimeModelBinderProvider());
    });

This way the NodaTime can work with the input type datetime-local, however since it doesn’t deal with seconds, it is always 00.

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật