Field saves only date and part of time is "zeroed"

Asked

Viewed 745 times

0

I have this part of code in my view.

<div class="form-group">
            @*@Html.LabelFor(model => model.DT_AGENDAMENTO, htmlAttributes: new { @class = "control-label col-md-2" })*@
            @Html.Label("Data de Agendamento", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DT_AGENDAMENTO, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DT_AGENDAMENTO, "", new { @class = "text-danger" })
            </div>
        </div>

And I have this code on my controller:

public async Task<ActionResult> Create([Bind(Include = "ID_SOLIC_RELATORIO,ID_RELATORIO,ID_USUARIO,DT_SOLICITACAO,DT_AGENDAMENTO,DT_GERACAO,BL_RELATORIO")] POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO)
        { 
            if (ModelState.IsValid)
            {
                db.POC_SOLIC_RELATORIO.Add(pOC_SOLIC_RELATORIO);
                //pOC_SOLIC_RELATORIO.BL_RELATORIO = AbrirExecutavelExtrairPdf();
                pOC_SOLIC_RELATORIO.DT_SOLICITACAO = DateTime.Now;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            ViewBag.ID_RELATORIO = new SelectList(db.POC_RELATORIO, "ID_RELATORIO", "NM_RELATORIO", pOC_SOLIC_RELATORIO.ID_RELATORIO);
            return View(pOC_SOLIC_RELATORIO);
        }

Using Chrome dev tools, I inspected this field and had this:

<input class="form-control text-box single-line" data-val="true" data-val-date="The field DT_AGENDAMENTO must be a date." data-val-required="O campo DT_AGENDAMENTO é obrigatório." id="DT_AGENDAMENTO" name="DT_AGENDAMENTO" type="datetime" value="">

The problem is that when I record in the bank the date coming from that textbox, records only the date part and the time comes "reset". How do I save Date and Time?

EDIT Below the complete Controller code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Relatorio.Models;
using System.IO;
using System.Diagnostics;

namespace Relatorio.Controllers
{
    public class AppealReportController : Controller
    {
        private ReportDBContext db = new ReportDBContext();
        private byte[] PdfFile = null;
        ModelFiles oModelFiles = new ModelFiles();

        // GET: AppealReport
        public async Task<ActionResult> Index()
        {
            var pOC_SOLIC_RELATORIO = db.POC_SOLIC_RELATORIO.Include(p => p.POC_RELATORIO);
            return View(await pOC_SOLIC_RELATORIO.ToListAsync());
        }

        // GET: AppealReport/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO = await db.POC_SOLIC_RELATORIO.FindAsync(id);
            if (pOC_SOLIC_RELATORIO == null)
            {
                return HttpNotFound();
            }
            return View(pOC_SOLIC_RELATORIO);
        }

        // GET: AppealReport/Create
        public ActionResult Create()
        {
            ViewBag.ID_RELATORIO = new SelectList(db.POC_RELATORIO, "ID_RELATORIO", "NM_RELATORIO");
            //var _arquivos = oModelFiles.GetFileReport();
            return View();
        }

        // POST: AppealReport/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 async Task<ActionResult> Create([Bind(Include = "ID_SOLIC_RELATORIO,ID_RELATORIO,ID_USUARIO,DT_SOLICITACAO,DT_AGENDAMENTO,DT_GERACAO,BL_RELATORIO")] POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO)
        { 
            if (ModelState.IsValid)
            {
                db.POC_SOLIC_RELATORIO.Add(pOC_SOLIC_RELATORIO);
                //pOC_SOLIC_RELATORIO.BL_RELATORIO = AbrirExecutavelExtrairPdf();
                pOC_SOLIC_RELATORIO.DT_SOLICITACAO = DateTime.Now;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            ViewBag.ID_RELATORIO = new SelectList(db.POC_RELATORIO, "ID_RELATORIO", "NM_RELATORIO", pOC_SOLIC_RELATORIO.ID_RELATORIO);
            return View(pOC_SOLIC_RELATORIO);
        }

        // GET: AppealReport/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO = await db.POC_SOLIC_RELATORIO.FindAsync(id);
            if (pOC_SOLIC_RELATORIO == null)
            {
                return HttpNotFound();
            }
            ViewBag.ID_RELATORIO = new SelectList(db.POC_RELATORIO, "ID_RELATORIO", "NM_RELATORIO", pOC_SOLIC_RELATORIO.ID_RELATORIO);
            return View(pOC_SOLIC_RELATORIO);
        }

        // POST: AppealReport/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 async Task<ActionResult> Edit([Bind(Include = "ID_SOLIC_RELATORIO,ID_RELATORIO,ID_USUARIO,DT_SOLICITACAO,DT_AGENDAMENTO,DT_GERACAO,BL_RELATORIO")] POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO)
        {
            if (ModelState.IsValid)
            {
                db.Entry(pOC_SOLIC_RELATORIO).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewBag.ID_RELATORIO = new SelectList(db.POC_RELATORIO, "ID_RELATORIO", "NM_RELATORIO", pOC_SOLIC_RELATORIO.ID_RELATORIO);
            return View(pOC_SOLIC_RELATORIO);
        }

        // GET: AppealReport/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO = await db.POC_SOLIC_RELATORIO.FindAsync(id);
            if (pOC_SOLIC_RELATORIO == null)
            {
                return HttpNotFound();
            }
            return View(pOC_SOLIC_RELATORIO);
        }

        // POST: AppealReport/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            POC_SOLIC_RELATORIO pOC_SOLIC_RELATORIO = await db.POC_SOLIC_RELATORIO.FindAsync(id);
            db.POC_SOLIC_RELATORIO.Remove(pOC_SOLIC_RELATORIO);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        //public void openApplication()
        //{
        //    System.Diagnostics.Process.Start("C:\\Projetos\\Servicos\\bin\\Servicos.exe");
        //}

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

        protected static byte[] AbrirExecutavelExtrairPdf()
        {
            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"C:\Projetos\Servicos\bin\Debug\Servicos.exe",
                    Arguments = "",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    WorkingDirectory = @"C:\Projetos\Servicos\bin\Debug",
                    CreateNoWindow = true
                }
            };
            proc.Start();

            using (var ms = new MemoryStream())
            {
                using (var sOut = proc.StandardOutput.BaseStream)
                {
                    byte[] buffer = new byte[4096];
                    int read;

                    while ((read = sOut.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                }

                string error = proc.StandardError.ReadToEnd();

                if (ms.Length == 0)
                {
                    throw new Exception(error);
                }

                proc.WaitForExit();

                return ms.ToArray();
            }
        }

        public FileResult Download(int ID_SOLIC_RELATORIO, string NM_RELATORIO)
        {
            int _arquivoId = ID_SOLIC_RELATORIO;
            var arquivos = oModelFiles.GetFileReport(ID_SOLIC_RELATORIO, NM_RELATORIO);

            //string nomeArquivo = (from arquivo in arquivos
            //                      where arquivo. == _arquivoId
            //                      select arquivo.arquivoCaminho).First();

            //string nomeArquivo = (from arquivo in db.POC_SOLIC_RELATORIO
            //                      where arquivo.ID_SOLIC_RELATORIO == ID_SOLIC_RELATORIO
            //                      select arquivo.BL_RELATORIO).First().ToString();

            string contentType = "application/pdf";
            //Os parametros para o arquivo são
            //1. o caminho do aruivo on servidor
            //2. o tipo de conteudo do tipo MIME
            //3. o parametro para o arquivos salvo pelo navegador
            return File(arquivos, contentType, "novoreport.pdf");
        }
    }
}
  • This came from dev Tools, Network tab: __Requestverificationtoken:Z47uxlbh3rjsi-Rlulmfzw48i62n2dxp9j_fovfpvratuoqc9gix4ye_4pag03_lk7occ4urskoegflhf6owyyy02dtkphk3menpjyoqwu1 ID_SOLIC_RELATORIO:3 ID_RELATORIO:1 ID_USUARIO:3 DT_AGENDAMENTO:09/11/2015 The time part is empty or null

  • Which database? What kind of data is in the database?

  • @jbueno, we use Oracle 11g. The field is of the Date type. But if I give a Datetime.Now, it records Date and Time. So the guy is right, the problem is, I believe, in the application.

  • 1

    How are you typing this date into input? Ex: 11/11/2015 or 11/11/2015 11:10:30:345 ?

  • If you are using Dataannotations, post what is on DT_AGENDAMENTO.

  • @Randrade, this controller was assembled by Visual 2013. What I’m doing is just a POC to demonstrate the company. The action that records in the comic book was the one I put in the post, I don’t know if that’s what you want. I will post the entire code of the controller because I don’t know what exactly you are asking for. I will edit the post.

  • My question is how you are filling in the field (manually). You are probably only filling in the date.

Show 2 more comments

2 answers

3


I am assigning that you are using Datetime for dates.

I see nothing wrong in your code, I believe you are not passing the values to time in your input.

I think you’re filling in this way: Como esta

When you should fill it out like this: inserir a descrição da imagem aqui

  • 1

    BIOS is a serious problem. Thanks Randrade. That’s right, if I am filling the date, the system has no way to set the time. A Datetime.Now is different, because I already pass the date and time. It was a hell of an imbecility.

  • @pnet This is more common than you think. Now, I advise you to add a mask or a datepicker (I think better this one). Imagine the user having to type SPACE whenever filling?

  • So there’s more, I don’t know why else is only accepting date in American format. I think a datepicker solves this.

  • @pnet There are some ways to solve this. That quest has some questions. If you do not find any that explain to you, open one that I will be happy to explain better

-1

You create a database and put a date field and an hour field and you put the type of it sweep.

And in php you put the following code. And then you create a database date and a table contacts.

<?php
$host = "localhost";
$user = "root";
$pass = "";
$banco = "data";

$conexao = mysql_connect($host,$user,$pass,$banco);

   $data = date("Y-m-d H:i");
   $hora = date('H:i');
   $query = "insert into contatos (data, hora) values ('{$data}', '{$hora}')";
   mysqli_query($conexao, $query);

                mysqli_close($conexao);
  • I can’t do that. The bank is already created and we are not allowed to create a bank and this one has 2500 tables and what you said is impossible for our reality here. See, if I give a datetime.now, it works. So the problem is not in the bank and yes, in the way I am formatting the date and sending to the bank. That’s where I should be working.

  • Lucas, welcome to [en.so]. Stay tuned for the question tags, this question is about ASP.NET (C#) and you gave an answer in PHP. Not to mention that your answer asks the questioner to make changes to the data model (which is not feasible most of the time). I’m glad you’re trying to help and don’t worry, the beginning is a bit tricky indeed. Maybe the page [Answer] can help you...

Browser other questions tagged

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