Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

Problemas com atributos DateTime

Os atributos DateTime não funcionam direito quando se trata de uma tela de edição com data anterior já preenchida.

2 respostas

Qual o problema que você está passando, Jaqueline? Não ficou claro o que não está funcionando. Pode pode colocar o exemplo completo aqui?

solução!

No model Tarefa: Tem duas colunas do Tipo DateTime.

public Tarefa()
        [Key]
        public int ID { get; set; }

        [Required]
        public int TipoTarefaID { get; set; }
        public virtual TipoTarefa TipoTarefa { get; set; }

        [Required]
        public string Assunto { get; set; }

        [Required, DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DataCriacao { get; set; }

        [Required, StringLength(128)]
        public string ApplicationUserId { get; set; }
        public ApplicationUser Usuario { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? DataConclusao { get; set; }        
    }

Quando abro a View Create, aparece o date-picker e consigo escolher uma data e ela é gravada. Tudo Correto.

Mas quando tento abrir a View Edit no registro gravado, que já deveria vir com os dados gravados, todos os campos mostram-se corretamente, exceto os campos Data.

Abaixo cópia das Views e do Controller:

@model Projeto.Models.Cadastros.Tarefa

@{
    ViewBag.Title = "Tarefas";
}

<h2>Cadastrar nova Tarefa</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.TipoTarefaID, "Tipo de Tarefa", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div id="divDropTiposTarefa">
                    @Html.Action("RecarregarDropDownList", "TiposTarefa")
                </div>
                @Ajax.ActionLink(" ", "CreateModal", "TiposTarefa", null, new AjaxOptions { UpdateTargetId = "modaldropbody", OnComplete = "openModal" }, new { @class = "glyphicon glyphicon-plus" })
                @Html.ValidationMessageFor(model => model.TipoTarefaID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Assunto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.Assunto, new { htmlAttributes = new { @class = "form-control" } })*@
                @Html.TextAreaFor(model => model.Assunto, 5, 40, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Assunto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DataCriacao, "Data da Inserção" , htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { @class = "form-control, date-picker" } })
                @Html.ValidationMessageFor(model => model.DataCriacao, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ApplicationUserId, "Criador", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ApplicationUserId", null, "Selecione um usuário", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ApplicationUserId, "", new { @class = "text-danger" })
            </div>
        </div>

       @*<div class="form-group">
            @Html.LabelFor(model => model.DataConclusao, "Data da Conclusão", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DataConclusao, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DataConclusao, "", new { @class = "text-danger" })
            </div>
        </div>*@

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Cadastrar" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink(" ", "Index", null, new { @class = "glyphicon glyphicon-arrow-left" })
</div>

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
@model Projeto.Models.Cadastros.Tarefa

@{
    ViewBag.Title = "Tarefas";
}

<h2>Alterar esta Tarefa</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

        <div class="form-group">
            @Html.LabelFor(model => model.TipoTarefaID, "Tipo de Oportunidade", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div id="divDropTiposTarefa">
                    @Html.Action("RecarregarDropDownList", "TiposTarefa")
                </div>
                @Ajax.ActionLink(" ", "CreateModal", "Tarefas", null, new AjaxOptions { UpdateTargetId = "modaldropbody", OnComplete = "openModal" }, new { @class = "glyphicon glyphicon-plus" })
                @Html.ValidationMessageFor(model => model.TipoTarefaID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Assunto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.Assunto, new { htmlAttributes = new { @class = "form-control" } })*@
                @Html.TextAreaFor(model => model.Assunto, 5, 40, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Assunto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DataCriacao, "Data da Criação", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DisplayFor(model => model.DataCriacao)
                @*@Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { @class = "form-control, datepicker" } })
                @Html.ValidationMessageFor(model => model.DataCriacao, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ApplicationUserId, "Criador", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DisplayFor(model => model.Usuario.Nome)
                @*@Html.DropDownList("ApplicationUserId", null, "Selecione um usuário", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ApplicationUserId, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DataConclusao, "Data de conclusão", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DataConclusao, new { htmlAttributes = new { @class = "form-control, date-picker" } })
                @Html.ValidationMessageFor(model => model.DataConclusao, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Gravar" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink(" ", "Index", null, new { @class = "glyphicon glyphicon-arrow-left" })
</div>

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
namespace Projeto.Controllers
{
    public class TarefasController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Tarefas
        public ActionResult Index()
        {
            var tarefas = db.Tarefas.Include(t => t.Cliente).Include(t => t.Processo).Include(t => t.TipoTarefa).Include(t => t.Usuario);
            return View(tarefas.ToList());
        }

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

        // GET: Tarefas/Create
        public ActionResult Create()
        {

            ViewBag.TipoTarefaID = new CBMMSapp.DAO.TiposTarefaDAO().ListaParaDropDown();

           ViewBag.ApplicationUserId = new CBMMSapp.DAO.UsuariosDAO().ListaParaDropDown();

            return View();
        }

        // POST: Tarefas/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,TipoTarefaID,Assunto,DataCriacao,ApplicationUserId,ClienteID,ProcessoID,DataConclusao")] Tarefa tarefa)
        {
            if (ModelState.IsValid)
            {
                db.Tarefas.Add(tarefa);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.TipoTarefaID = new CBMMSapp.DAO.TiposTarefaDAO().ListaParaDropDown( tarefa.TipoTarefaID);

            //ViewBag.ApplicationUserId = new CBMMSapp.DAO.UsuariosDAO().ListaParaDropDown(tarefa.ApplicationUserId);

            return View(tarefa);
        }

        // GET: Tarefas/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Tarefa tarefa = db.Tarefas.Include(p => p.Usuario).SingleOrDefault(s => s.ID == id);

            if (tarefa == null)
            {
                return HttpNotFound();
            }
            ViewBag.TipoTarefaID = new CBMMSapp.DAO.TiposTarefaDAO().ListaParaDropDown( tarefa.TipoTarefaID);
            ViewBag.ApplicationUserId = new CBMMSapp.DAO.UsuariosDAO().ListaParaDropDown(tarefa.ApplicationUserId);
            return View(tarefa);
        }

        // POST: Tarefas/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,TipoTarefaID,Assunto,DataCriacao,ApplicationUserId,ClienteID,ProcessoID,DataConclusao")] Tarefa tarefa)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tarefa).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.TipoTarefaID = new CBMMSapp.DAO.TiposTarefaDAO().ListaParaDropDown(tarefa.TipoTarefaID);
            ViewBag.ApplicationUserId = new CBMMSapp.DAO.UsuariosDAO().ListaParaDropDown(tarefa.ApplicationUserId);
            return View(tarefa);
        }

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

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

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