Fill date Automatically in ASP.NET MVC 5

Asked

Viewed 610 times

1

Hello, all right? I need some help from you, I already searched here on the forum but I was not successful with the results. I have a small application where I control Digital Certificates, my Certificate model is simple as below:

Entity Framework Usage and Migrations with SQL SERVER.

Follow my Model:

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace ControleGCD.Models

{
    public class Certificado
    {

        [Key]
        public int CertificadoId { get; set; }
    [Display(Name ="Chave")]
    [MinLength(10,ErrorMessage ="{0} deve conter no mínimo 10 caracteres.")]
    [StringLength(50, ErrorMessage ="{0} deve conter entre 10 até 50 caracteres.")]
    [Required(ErrorMessage ="Favor preencher a {0} do Certificado")]
    public string CertificadoChave { get; set; }

    [Display(Name = "Descrição")]
    [MinLength(10, ErrorMessage = "{0} deve conter no mínimo 10 caracteres.")]
    [StringLength(50, ErrorMessage = "{0} deve conter entre 10 até 50 caracteres.")]
    [Required(ErrorMessage = "Favor preencher a {0} do Certificado")]
    public string CertificadoDescricao { get; set; }

    [Display(Name = "Preço")]
    [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false, NullDisplayText = "Sem preço")]
    public decimal CertificadoPreco { get; set; }

    [Display(Name = "Compra")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]    
    public DateTime CertificadoDtCompra { get; set; }

    [Display(Name = "Vencimento")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime CertificadoDtVencimento { get; set; }

    [Display(Name = "Cadastro")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime CertificadoDtCadastro { get; set; }

    [Display(Name = "Expira em (dias)")]
    public int CertificadoExpira { get { return (int)CertificadoDtVencimento.Subtract(CertificadoDtCompra).TotalDays; } }

    [Display(Name ="Status")]
    public StatusCertificado CertificadoStatus { get; set; }

    [Display (Name = "Tipo")]
    public int TipoCertificadoId { get; set; }
    public virtual TipoCertificado TipoCertificado { get; set; }

    [Display(Name = "Modelo")]
    public int ModeloCertificadoId { get; set; }
    public virtual ModeloCertificado ModeloCertificado { get; set; }

    [Display(Name = "Fornecedor")]
    public int FornecedorId { get; set; }

Note that in it I have a registration date field where I want to fill automatically with the current date and show in View create.

Follows my View:

@model ControleGCD.Models.Certificado
@{
    /**/

ViewBag.Title = "Cadastro";
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cadastro  - Certificado Digital</title>
    <link rel="stylesheet" href="~/Content/bootstrap.min.css">
    <link rel="stylesheet" href="~/Content/formulario.css">
</head>

<body>
    <div class="form-container">
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
        <br />
        <div class="panel panel- panel-primary">

            <div class="panel-heading">
                <h4>Cadastro Certificado Digital</h4>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="form-group col-md-3">
                        @Html.LabelFor(model => model.CertificadoChave, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoChave, new { htmlAttributes = new { @class = "form-control", placeholder = "Chave do Certificado" } })
                        @Html.ValidationMessageFor(model => model.CertificadoChave, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group col-md-4">
                        @Html.LabelFor(model => model.CertificadoDescricao, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoDescricao, new { htmlAttributes = new { @class = "form-control", placeholder = "Descrição" } })
                        @Html.ValidationMessageFor(model => model.CertificadoDescricao, "", new { @class = "text-danger" })
                    </div>



                    <div class="form-group col-md-4">
                        @Html.LabelFor(model => model.FornecedorId, htmlAttributes: new { @class = "control-label" })
                        @Html.DropDownList("FornecedorId", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.FornecedorId, "", new { @class = "text-danger" })
                    </div>


                </div>
                <div class="row">
                    <div class="form-group col-md-3">
                        @Html.LabelFor(model => model.CertificadoStatus, htmlAttributes: new { @class = "control-label" })
                        @Html.EnumDropDownListFor(model => model.CertificadoStatus, new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.CertificadoStatus, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group col-md-2">
                        @Html.LabelFor(model => model.TipoCertificadoId, "TipoCertificadoId", htmlAttributes: new { @class = "control-label" })
                        @Html.DropDownList("TipoCertificadoId", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.TipoCertificadoId, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group col-md-2">
                        @Html.LabelFor(model => model.ModeloCertificadoId, "ModeloCertificadoId", htmlAttributes: new { @class = "control-label" })
                        @Html.DropDownList("ModeloCertificadoId", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.ModeloCertificadoId, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group col-md-4">
                        @Html.LabelFor(model => model.CertificadoPreco, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoPreco, new { htmlAttributes = new { @class = "form-control", placeholder = "0,00", data_tipo = "moeda" } })
                        @Html.ValidationMessageFor(model => model.CertificadoPreco, "", new { @class = "text-danger" })
                    </div>
                </div>
                <hr />
                <div class="row">
                    <div class="form-group col-md-2">
                        @Html.LabelFor(model => model.CertificadoDtCompra, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoDtCompra, new { htmlAttributes = new { @class = "form-control", placeholder = "Data Compra" } })
                        @Html.ValidationMessageFor(model => model.CertificadoDtCompra, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group col-md-2">
                        @Html.LabelFor(model => model.CertificadoDtVencimento, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoDtVencimento, new { htmlAttributes = new { @class = "form-control", placeholder = "Data Vencimento" } })
                        @Html.ValidationMessageFor(model => model.CertificadoDtVencimento, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group col-md-2">
                        @Html.LabelFor(model => model.CertificadoDtCadastro, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.CertificadoDtCadastro, new { htmlAttributes = new { @class = "form-control", placeholder = "Data Cadastro" } })
                        @Html.ValidationMessageFor(model => model.CertificadoDtCadastro, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="panel-footer">
                    <input type="submit" value="Cadastrar" class="btn btn-primary">
                    @Html.ActionLink("Voltar", "Index")
                </div>
            </div>
        </div>
    }

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script src="~/Scripts/jquery-3.1.1.min.js"></script>
        <script src="~/Scripts/jquery.mask.min.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script src="~/Scripts/mascaras.js"></script>
        <script src="~/Scripts/methods_pt.js"></script>
    }
</div>

Follow my Controller:

using Controlegcd.Context; using Controlegcd.Models; using System; using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Mvc;

namespace Controlegcd.Controllers { public class Certificadoscontroller : Controller { private Controlegcdcontext db = new Controlegcdcontext();

    // GET: Certificados
    public ActionResult Index()
    {
        var certificados = db.Certificados.Include(c => c.Fornecedor).Include(c => c.ModeloCertificado).Include(c => c.TipoCertificado);
        return View(certificados.ToList());
    }

    // GET: Certificados/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Certificado certificado = db.Certificados.Find(id);
        if (certificado == null)
        {
            return HttpNotFound();
        }
        return View(certificado);
    }

    // GET: Certificados/Create
    public ActionResult Create()
    {
        ViewBag.FornecedorId = new SelectList(db.Fornecedores, "FornecedorId", "FornecedorNome");
        ViewBag.ModeloCertificadoId = new SelectList(db.ModeloCertificados, "ModeloCertificadoId", "ModeloCertificadoDescricao");
        ViewBag.TipoCertificadoId = new SelectList(db.TipoCertificados, "TipoCertificadoId", "TipoCertificadoDescricao");
        Certificado certificado = new Certificado();
        certificado.CertificadoDtCadastro = DateTime.Now;
        return View();
    }

       // POST: Certificados/Create
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "CertificadoId,CertificadoChave,CertificadoDescricao,CertificadoPreco,CertificadoDtCompra,CertificadoDtVencimento,CertificadoDtCadastro,CertificadoStatus,TipoCertificadoId,ModeloCertificadoId,FornecedorId")] Certificado certificado)
    {
        if (ModelState.IsValid)
        {
            db.Certificados.Add(certificado);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.FornecedorId = new SelectList(db.Fornecedores, "FornecedorId", "FornecedorNome", certificado.FornecedorId);
        ViewBag.ModeloCertificadoId = new SelectList(db.ModeloCertificados, "ModeloCertificadoId", "ModeloCertificadoDescricao", certificado.ModeloCertificadoId);
        ViewBag.TipoCertificadoId = new SelectList(db.TipoCertificados, "TipoCertificadoId", "TipoCertificadoDescricao", certificado.TipoCertificadoId);
        return View(certificado);
    }

    // GET: Certificados/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Certificado certificado = db.Certificados.Find(id);
        if (certificado == null)
        {
            return HttpNotFound();
        }
        ViewBag.FornecedorId = new SelectList(db.Fornecedores, "FornecedorId", "FornecedorNome", certificado.FornecedorId);
        ViewBag.ModeloCertificadoId = new SelectList(db.ModeloCertificados, "ModeloCertificadoId", "ModeloCertificadoDescricao", certificado.ModeloCertificadoId);
        ViewBag.TipoCertificadoId = new SelectList(db.TipoCertificados, "TipoCertificadoId", "TipoCertificadoDescricao", certificado.TipoCertificadoId);
        return View(certificado);
    }

    // POST: Certificados/Edit/5
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "CertificadoId,CertificadoChave,CertificadoDescricao,CertificadoPreco,CertificadoDtCompra,CertificadoDtVencimento,CertificadoDtCadastro,CertificadoStatus,TipoCertificadoId,ModeloCertificadoId,FornecedorId")] Certificado certificado)
    {
        if (ModelState.IsValid)
        {
            db.Entry(certificado).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.FornecedorId = new SelectList(db.Fornecedores, "FornecedorId", "FornecedorNome", certificado.FornecedorId);
        ViewBag.ModeloCertificadoId = new SelectList(db.ModeloCertificados, "ModeloCertificadoId", "ModeloCertificadoDescricao", certificado.ModeloCertificadoId);
        ViewBag.TipoCertificadoId = new SelectList(db.TipoCertificados, "TipoCertificadoId", "TipoCertificadoDescricao", certificado.TipoCertificadoId);
        return View(certificado);
    }

    // GET: Certificados/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Certificado certificado = db.Certificados.Find(id);
        if (certificado == null)
        {
            return HttpNotFound();
        }
        return View(certificado);
    }

    // POST: Certificados/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Certificado certificado = db.Certificados.Find(id);
        db.Certificados.Remove(certificado);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

I’m picking up on this... Automatically fill in the Registration Date Field with the current date. Can you help me please?

Grateful.

1 answer

0

The most "clean" way to send a default value to the form, is to create an instance of the object and popular with the default values when giving the GET in the form ACTION:

public IActionResult Cadastrar() {
   Certificado certificado = new Certificado();
   certificado.CertificadoDtCadastro = DateTime.Now;

   return View(certificado);
}
  • Replace the method name with the correct one.

This way you can also centralize the default values of your object.

  • No problem, should work the same way, exchange Iactionresult for Actionresult

  • Gustavo, Add the two lines, the only difference is in the Return I left: Return View(). When I specified the certified obj within the parentheses it was an error. Leaving empty, the system was compiled normally and ran without showing the date.. What did I do wrong? Do I have to go through my View? Thanks again.

  • Post your controller code

  • Add my Controller to the body of my question Gustavo.

  • 1

    Strange to have given build error when adding Return View(certificate), as you use it yourself in other methods

  • Gustavo, Thank you very much man...I certainly ate ball in something... reviewing here refiz as you instructed me and it worked. I thank you.

  • Please give the answer as accept friend :)

Show 2 more comments

Browser other questions tagged

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