Save time of registration in the database

Asked

Viewed 141 times

0

I have a form and whenever someone register, I need to save the time of registration in my table Historico2 inside the property DateTime? Quando.

    public partial class Historico2
{
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    public string Quem { get; set; }

    public DateTime? Quando { get; set; }

    public decimal Peso { get; set; }

    public decimal Valor { get; set; }

    public decimal? TOTAL { get; set; }
}

How can I pass the amount DateTime.Now() whenever someone registers for the property DateTime? Quando?

Actionresult Create() from my controller:

        [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "ID,Quem,Quando,Peso,Valor,TOTAL")] Historico2 historico2)
    {
        if (ModelState.IsValid)
        {

            db.Historico2.Add(historico2);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(historico2);
    }

1 answer

3


Given the scenario the easiest way to solve the problem is to provide the date before adding the record to the context, as in the example below. But there are other alternatives like setting this value as default in the database itself or as in the repository Pattern where you would do it in your "salvar()". There are several ways to meet this requirement.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID,Quem,Quando,Peso,Valor,TOTAL")] Historico2 historico2)
{
    if (ModelState.IsValid)
    {
        historico2.Quando = DateTime.Now;            

        db.Historico2.Add(historico2);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(historico2);
}
  • Thanks Leandro! I understood the concept

Browser other questions tagged

You are not signed in. Login or sign up in order to post.