Home > Net >  DateOnly input for asp .net
DateOnly input for asp .net

Time:12-01

I'm using mvc .net core (.net 6.0) to create an app linked to a db and I have an issue : I scaffholded a controller and its views (create, edit...) but when I try to create an object to send to db with entity framework, the DateOnly typed fields won't work and put in this date for all dates I try to write : 292269055-12-03 (it seems to be the max value ?). I need to use DateOnly type for compatiblity reasons because the DB have date fields (I found this information here https://www.npgsql.org/doc/types/datetime.html and if I try to use datetime, it doesnt work).

There is my code : view :

<div class="form-group">
      <label asp-for="BirthDay" class="control-label"></label>
      <input asp-for="BirthDayUI" class="form-control" type="date"/>
      <span asp-validation-for="BirthDay" class="text-danger"></span>
</div>

controller (autogenerated) :

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,FirstName,BirthDay,Email,MobilePhone,LandLinePhone,PostalCity,PostalCode,PostalAdress,Gender,MedicalCertificate,MedicalCertificateStart,MedicalCertificateEnd,ProfilePicture")] Member member)
{
    if (ModelState.IsValid)
    {
        _context.Add(member);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
return View(member);
}

and finally, the model where I try to fiddle this :

[Required]
public DateOnly BirthDay { get; set; }
[NotMapped]
public DateTime BirthDayUI
{
   get => BirthDay.ToDateTime(new TimeOnly());

   set => BirthDay = DateOnly.FromDateTime(value);
}

The getter works perfectly but not the setter and I don't know what I must change.

thank you for helping me

CodePudding user response:

I have no experience yet with .NET 6, but I did some research about this. https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/

And I found next line

DateOnly d3 = DateOnly.ParseExact("31 Dec 1980", "dd MMM yyyy", CultureInfo.InvariantCulture);  // Custom format

Try to use this on your setter, like this:

set => BirthDay =  DateOnly.ParseExact(value.ToShortDateString(), "dd MMM yyyy", CultureInfo.InvariantCulture);

Don't forget to specify the format and cultureinfo

Let me known if this works!

CodePudding user response:

I finally found a solution : I created a UI version of my member model which use DateTime properties and bind my member controller on it (instead of member type) and i use a little function to cast it in my original member type. I named it memberviewmodel (but im not sure the name is pertinent).

        [HttpPost]
        [ValidateAntiForgeryToken]

            public async Task<IActionResult> Create([Bind("Id,Name,FirstName,BirthDay,Email,MobilePhone,LandLinePhone,PostalCity,PostalCode,PostalAdress,Gender,MedicalCertificate,MedicalCertificateStart,MedicalCertificateEnd,ProfilePicture")] **MemberViewmodel membervm**)
            {
                Member member = ModelViewmodelConverter.MemberViewmodelToMember(membervm);
                if (ModelState.IsValid)
                {
                    _context.Add(member);

                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
                return View(member);
            }

the function :

 public static Member MemberViewmodelToMember(MemberViewmodel vm)
        {
            Member result = new Member()
            {
                ...
                BirthDay = DateOnly.FromDateTime(vm.BirthDay),
                ...
            }
            return result;
        }
  • Related