Waller
Waller

Reputation: 476

Unable to update date due to format in MVC

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.

Upvotes: 0

Views: 434

Answers (2)

Waller
Waller

Reputation: 476

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" })

Upvotes: 0

Serge
Serge

Reputation: 43890

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"}) 

Upvotes: 1

Related Questions