Search code examples
.netasp.net-corerazordata-annotations

How to handle data format for a DateTime field in the model for ASP.NET razor page with Arabic culture


While I set the Arabic language at that time my modifyOn/createOn date property throws an invalid state (for English it's working fine).

if (model.isValid) 

returns false even when date is valid, but in Arabic character below is the screenshot of validate mode of all property.

Property which I define in my model

enter image description here

.cshtml HiddenFor HTML markup:

enter image description here

Screenshot of validation:

enter image description here


Solution

  • This is a problem with unrecognized dates due to different calendar formats. You can add DateTimeFormat to specific CultureInfo, like this:

    var culture = CultureInfo.CreateSpecificCulture("ar-AE");
    var dateformat = new DateTimeFormatInfo
    {
        LongDatePattern = "yyyy-MM-dd HH:mm"
    };
    culture.DateTimeFormat = dateformat;
    
    var supportedCultures = new[]
    {
        culture
    };
    
    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture(culture),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
    });
    

    My test code in controller:

    public IActionResult Create(TestModel model)
    {
        if(ModelState.IsValid)
        {
            foreach(var item in model.Input.BookRoles)
            {
                var rqf = Request.HttpContext.Features.Get<IRequestCultureFeature>();
                var culture = rqf.RequestCulture.Culture;
                var DataString = item.CreatedOn.ToLongDateString();
            }
        }
        return View();
    }
    

    Test Result:

    enter image description here