Using DateTimeOffset in a DateTimePicker and Grid
Environment
| Product | DateTimePicker for Progress Telerik UI for ASP.NET Core, Grid for Progress Telerik UI for ASP.NET Core |
Description
How can I bind a DateTimeOffset model value to the Telerik UI for ASP.NET Core DateTimePicker and Data Grid components?
Solution
The DateTimeOffset structure represents a new date-time data structure that defines a point relative to the UTC time zone. However, neither databases nor JS are able of storing this structure as is because the DateTimeOffset is serialized as an object. The UI for ASP.NET Core components that use dates depend on the JavaScript Date type API, which means that they need to work with a JavaScript Date.
The default MVC binder is capable of binding a DateTimeOffset only if the submitted parameter is in the 2017-04-17T05:04:18.070Z format. In other words, if the UI for ASP.NET Core components implement the DateTimeOffset overload, their use will be limited only to the above format or they will require a custom binder.
To achieve the desired results, map database models with DateTimeOffset fields to view models with DateTime fields and use those view models in the Telerik UI for ASP.NET Core components. AutoMapper is a popular third-party library that can map the models as shown below.
-
Install AutoMapper from NuGet Package Manager or from the package manager console:
RazorPM> Install-Package AutoMapperUpon a successful installation, the
csprojfile should include a similar package:html<PackageReference Include="AutoMapper" Version="9.0.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" /> -
Add a Mapping profile class that inherits from
AutoMapper.Profileand list the required mappings.C#public class MappingProfile : Profile { public MappingProfile() { CreateMap<Car, CarViewModel>(); CreateMap<CarViewModel, Car>(); CreateMap<DateTime, DateTimeOffset>().ConstructUsing(x => new DateTimeOffset(x)); CreateMap<DateTimeOffset, DateTime>(); } }
For the complete implementation, refer to this GitHub project.