0

Snippet from Model

    [Display(Name = "Updated Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public Nullable<DateTime> updatedAt { get; set; }

Snippet from Controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(NcRecordClass model)
    {
        if (ModelState.IsValid)
        {
            var NcRecord = new NcRecordClass()
            {
                Id = model.Id,
                updatedAt = model.updatedAt,
                note = model.note
            };

            db.Entry(NcRecord).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Edit", new { id = model.Id, update = true });
        }
        return View(model);
    }

Snippet from View

 @Html.TextBoxFor(model => model.updatedAt, @"{0:dd\/MM\/yyyy}", new { @class = "form-control" })

When I try to update this column using the value '25/11/2020' , this warning will come out

The value '25/11/2020' is not valid for Updated Date.

I want to use the dd/MM/yyyy format in the application.
By the way, I use Postgres DB for this project (Datatype for updatedAt is 'timestamp without time zone'.
I have a similar project using the same code, the only difference is that project is using MSSQL server. And that project have no problem like this.

Waller
  • 433
  • 1
  • 6
  • 20
  • Try @Html.TextBoxFor(m => m.updatedAt,"{0:dd/MM/yyyy}", new { type = "date" , class = "form-control"}) – Serge Nov 13 '20 at 15:28
  • In `psql` do `SHOW datestyle` or `select * from pg_settings where name ='DateStyle'; ` . My guess is you have a style that is `MDY` not `DMY`. – Adrian Klaver Nov 13 '20 at 15:34

2 Answers2

1

The [DisplatFormat] attribute is only respected when using DisplayFor() or EditorFor(). To format a value using TextBoxFor(), you need to use an overload that accepts a format string:


@Html.TextBoxFor(m => m.updatedAt,"{0:dd/MM/yyyy}", new { type = "date" , class = "form-control"}) 

Serge
  • 40,935
  • 4
  • 18
  • 45
0

Answer by Sergey partly helped. When I put the type = "date", the textbox become a datepicker which was even better, and I can update the date. But the problem was after I update, the value shown on the textbox was "dd/mm/yyyy" literally. Then I found out that The date of an html input element of type date must be formatted in respect to ISO8601, which is: yyyy-MM-dd Link Here . So finally, the code that work is this:

@Html.TextBoxFor(model => model.updatedAt, @"{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" })
Waller
  • 433
  • 1
  • 6
  • 20