Decimal type field Entity Framework ASP.NET MVC

Asked

Viewed 427 times

-1

I have a table called Pecas where only has name and value, but when I click create new piece is not saving in the database, appears the msg that was added but is not entering, in debug shows the name but the value is always getting 0 no matter the value I put.

Table

    public class Pecas
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public decimal ValorUnitatio { get; set; }


}

Tablet

        public PecasVM()
    {

    }

    public PecasVM(Pecas row)
    {
        Id = row.Id;
        Nome = row.Nome;
        ValorUnitatio = row.ValorUnitatio;

    }

    public int Id { get; set; }
    public string Nome { get; set; }
    public decimal ValorUnitatio { get; set; }

My controller

        public ActionResult Criar()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Criar(PecasVM model)
    {
        if (ModelState.IsValid)
        {
            using (Db db = new Db())
            {
                Pecas pec = new Pecas();

                pec.Nome = model.Nome;
                pec.ValorUnitatio = model.ValorUnitatio;

                db.Pecas.Add(pec);
                db.SaveChanges();

            }
        }

        TempData["MSG"] = "Peça adicionada com sucesso.";
        return RedirectToAction("Index");
    }
  • Some doubts: when you say value you are referring to ValorUnitario? If it is, it cannot be a conversion error since the value is decimal? Are you passing an integer value, no comma/dot? Still with zero value in ValorUnitario should enter normally because zero is an acceptable value. Id, I imagine he’s identity/sequence/auto_increment etc in your right bank?

  • Probably the json that arrives is coming as a string, since it cannot convert, it uses the default value of the decimal that is zero.

  • Have you tried to map the property as double?

  • He decided to work alone, without me changing anything, tried with a comma and a period and was not going and now this inserting.

  • certainly ... if (Modelstate.Isvalid) if it is invalid will show that entered

  • @As Cezarmdlosci solved "alone", it would not be better to close the question?

Show 1 more comment

1 answer

0

I resolved it as follows:

        public ActionResult Detalhes(int id)
    {


        ConsertoVM model;
        using (Db db= new Db())
        {

            decimal total = 0m;

            Conserto cons = db.Conserto.Find(id);
            decimal vPeca = cons.Pecas.ValorUnitatio;
            decimal maoObra = cons.ValorMaoObra;

            total += vPeca + maoObra;
            cons.ValorTotalConserto = total;

            model = new ConsertoVM(cons);
        }
        return View(model);
    }

of course it could be done otherwise but wanted to do so.

Browser other questions tagged

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