sqldatetime overflow c# When trying to use type = Date in Razor Using . NET MVC

Asked

Viewed 42 times

0

When trying to save a change from a client, the SQL Server database is returning the following message: Sqldatetime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

View: 
 <label>Data de nascimento:</label>
    @Html.TextBoxFor(model => model.DataNascimento, new { @class = "form-control col-md-2", type = "date" })

Model:         [Required(ErrorMessage = "Por favor, informe uma data de nascimento")]                    
        public DateTime DataNascimento { get; set; }

Controller: [HttpPost]
        public IActionResult Editar(EditarClienteModel model)
        {

            try
            {
                var cliente = new Cliente();
                var clienteRepository = new ClienteRepository();

                model.Nome = cliente.Nome;
                model.Email = cliente.Email;
                model.DataNascimento = cliente.DataNascimento;

                clienteRepository.Alterar(cliente);
                TempData["Mensagem"] = "Cliente alterado com sucesso";
            }
            catch(Exception e)
            {
                TempData["Mensagem"] = "Ocorreu um erro: " + e.Message;
            }


            return View();
        }

Can anyone shed any light on what might be going on? Ps: I’ve tried changing the type of column to datetime2, as I saw in another topic here, but it didn’t work

  • what has in the method change?

  • There’s no reason to change it to DateTime2, you have to debug the code and see what is receiving in cliente.DataNascimento

  • @Lucasmiranda This is the change code, I am using Dapper ORM in this case public void Alterar(Cliente cliente)&#xA; {&#xA; var query = "update Cliente set Nome = @Nome, Email = @Email, DataNascimento = @DataNascimento" +&#xA; " where IdCliente = @IdCliente";&#xA; &#xA; using (var connection = new SqlConnection(connectionString))&#xA; {&#xA; connection.Execute(query, cliente);&#xA; }

  • this code is very strange,it receives a model, instance a client, but does not pass the model data to the client, does the opposite, and tries to save the same client, IE, nothing will be changed there! should be for example cliente.Nome = model.Nome and not the other way around!

  • @Yes, thanks for the tip, I realized this mistake and changed. However, the reason for the error was that the Datetime input, in the view was receiving some extra information, being necessary to use a Model.DataNascimento.ToString("yyyy-MM-dd") After adding this, it worked normally! , there were some other errors in the controller as well, but the reason for this error in question, I believe it was just that same line

  • the other day Pedro, I don’t know if you’re using any Orms (entity-framework, nhibernate, etc), but if you pass the model data that came from the browser’s direct page to the bank and you don’t have a protection, your code is exposed to "SQL Injection"

  • I’m using the ORM Dapper, I don’t know if the way I’m doing my code would be vulnerable, but since you gave me the tip, I’ll research it! obg once again

Show 2 more comments

1 answer

0

Problem solved, thank you all! I will leave below what I changed in the code as it may help someone beginner like me.

//Na view: 
@Html.HiddenFor(model => model.IdCliente)
//HiddenFor para especificar para o controller, o ID do cliente que está sendo editado

<label>Data de nascimento:</label>
        @Html.TextBoxFor(model => model.DataNascimento, Model.DataNascimento.ToString("yyyy-MM-dd"), new { @class = "form-control col-md-4", @type = "date" })

//adicionei o Model.DataNascimento.ToString("yyyy-MM-dd") para formatar a data e enviar //corretamente para o banco

//No Controller: 

 cliente.IdCliente = model.IdCliente;
 cliente.Nome = model.Nome;
 cliente.Email = model.Email;
 cliente.DataNascimento = model.DataNascimento;

//a ordem estava invertida, estava pegando a model e transformando no valor do objeto //cliente, quando deveria ser o contrário para realizar o update. 

//Na model: 

public int IdCliente{ get; set; }
//get set necessário para validação do ID na model.

Browser other questions tagged

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