2

could anyone tell me what am I doing wrong? I am getting null properties trying to bind.

Explaining:

My Controller Index looks ok, so that in my View I can see all the input values that I want to bind filled (IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario).

So far, everything looks good. But, after submit the page, in my Controller CheckOut all the properties in checkOut object binded is null, as you can see in the picture.

enter image description here

It was working fine, I dont know what I did so that it now is getting null properties. I am using asp.net core 3.1 MVC

ViewModel

public class CheckOut
{
    public Usuario Usuario { get; set; }
    public UsuarioUnidade UsuarioUnidade { get; set; }
    public CatalogoEndereco CatalogoEndereco { get; set; }
    public UsuarioPagamento UsuarioPagamento { get; set; }

    public byte IdPedidoAtendimento { get; set; }
    public string PedidoAtendimentoNome { get; set; }
    public decimal PedidoAtendimentoTaxa { get; set; }
    public DateTime? HorarioAgendado { get; set; }

    public byte IdPedidoTipoPagamento { get; set; }
    public string PedidoTipoPagamento { get; set; }

    public int IdUnidadeUsuario { get; set; }

    public string Nome { get; set; }

    public string NumEndereco { get; set; }
    public string ComplementoEndereco { get; set; }
    public string RuaNome { get; set; }
    public string CidadeNome { get; set; }
    public string EstadoNome { get; set; }
    public string CEP { get; set; }

    public byte? isCPF { get; set; }
    public string CPF { get; set; }

    public string NumeroCartao { get; set; }
    public string CodCartao { get; set; }
}

Controller

    public IActionResult Index()
    {
        var user = User.FindFirst(ClaimTypes.Name);
        if (user != null)
        {
            Usuario usuario = new Usuario();
            usuario = _context.Usuario
                .SingleOrDefault(u => u.Email.Equals(user.Value) && u.IsAtivo == true);

            CatalogoEndereco catalogoEndereco = new CatalogoEndereco();
            catalogoEndereco = _context.CatalogoEndereco
               .Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsAtivo == true && c.IsPrincipal == true)
               .SingleOrDefault();

            UsuarioPagamento usuarioPagamento = new UsuarioPagamento();
            usuarioPagamento = _context.UsuarioPagamento
               .Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
               .SingleOrDefault();

            UsuarioUnidade usuarioUnidade = new UsuarioUnidade();
            usuarioUnidade = _context.UsuarioUnidade
               .Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IdUnidadeNavigation.IsAtiva == true && c.IsPrincipal == true)
               .SingleOrDefault();

            UsuarioAtendimento usuarioAtendimento = new UsuarioAtendimento();
            usuarioAtendimento = _context.UsuarioAtendimento
               .Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
               .SingleOrDefault();

            CheckOut checkOut = new CheckOut()
            {
                Usuario = usuario,
                UsuarioUnidade = usuarioUnidade,
                CatalogoEndereco = catalogoEndereco,
                UsuarioPagamento = usuarioPagamento,

                IdPedidoAtendimento = usuarioAtendimento.Tipo,
                PedidoAtendimentoNome = _context.PedidoAtendimento
                    .FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Nome,
                PedidoAtendimentoTaxa = _context.PedidoAtendimento
                    .FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Taxa

            };

            if (usuarioAtendimento.Tipo == 1)
            {
                checkOut.Nome = usuario.Nome; 

                if (usuarioUnidade != null)
                {
                    checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
                }

                if (catalogoEndereco != null)
                {
                    checkOut.RuaNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
                    checkOut.CidadeNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
                    checkOut.EstadoNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
                    checkOut.NumEndereco = catalogoEndereco.NumEndereco;
                    checkOut.ComplementoEndereco = catalogoEndereco.Complemento;
                    checkOut.CEP = catalogoEndereco.IdEnderecoLogradouroNavigation.Cep;
                }
            }
            else if (usuarioAtendimento.Tipo == 2)
            {
                if (usuarioUnidade != null)
                {
                    checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
                    checkOut.Nome = usuarioUnidade.IdUnidadeNavigation.Nome; 

                    checkOut.RuaNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
                    checkOut.CidadeNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
                    checkOut.EstadoNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
                    checkOut.NumEndereco = usuarioUnidade.IdUnidadeNavigation.NumEndereco;
                    checkOut.CEP = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.Cep;
                }
            }

            if (usuarioPagamento != null)
            {
                checkOut.IdPedidoTipoPagamento = usuarioPagamento.Tipo;
                checkOut.PedidoTipoPagamento = _context.PedidoTipoPagamento
                    .FirstOrDefault(t => t.IdPedidoTipoPagamento == usuarioPagamento.Tipo).Nome;

                checkOut.isCPF = 0;
                checkOut.CPF = usuario.Cpf;
                checkOut.NumeroCartao = null;
                checkOut.CodCartao = null;

                if (usuarioPagamento.Tipo == 1 || usuarioPagamento.Tipo == 2)
                {
                    checkOut.NumeroCartao = "**** " + usuarioPagamento.Numero.Substring(12, 4);
                    checkOut.CodCartao = null; 
                }
            }
            return View(checkOut);
        }
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CheckOut([Bind("IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario")] CheckOut checkOut)
    {
        if (ModelState.IsValid)
        {
            var user = User.FindFirst(ClaimTypes.Name);
            if (user != null)
            {
                var cliente = _context.Usuario.SingleOrDefault(u => u.Email.Equals(user.Value));

                var pedido = new Pedido()
                {
                    IdUsuario = cliente.IdUsuario,
                    IdUnidade = checkOut.IdUnidadeUsuario,
                    IdPedidoCanalVenda = 1,
                    IdPedidoAtendimento = checkOut.IdPedidoAtendimento, 
                    IdAtendente = null,
                    IdPedidoTipoPagamento = checkOut.IdPedidoTipoPagamento, 
                    IdEntregador = null,
                    IdPedidoStatus = 1, 
                    DataPedido = DateTime.Now,
                    DataEntrega = null,
                    HorarioAgendado = null,
                    TaxaServico = checkOut.PedidoAtendimentoTaxa
                };
                _context.Pedido.Add(pedido);
                await _context.SaveChangesAsync()
                .ConfigureAwait(false);
                int lastPedido = pedido.IdPedido;

                   List<Carrinho> cart = JsonSerializeSessionHelper.Get<List<Carrinho>>(HttpContext.Session, "cart");
                foreach (var item in cart)
                {
                    var pedidoItens = new PedidoItens
                    {
                        IdPedido = lastPedido,
                        IdProduto = item.IdProduto,
                        IdProdutoTamanho = item.IdProdutoTamanho,
                        IdProdutoTipoMassa = item.IdProdutoTipoMassa,
                        IdProdutoMeia = item.IdProdutoMeia,
                        Quantidade = item.Quantidade,
                        Preco = item.Preco
                    };
                    _context.PedidoItens.Add(pedidoItens);
                }
                await _context.SaveChangesAsync()
                    .ConfigureAwait(false);
                TempData["save"] = "Pedido realizado com sucesso";

                HttpContext.Session.Remove("cart");
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
            return RedirectToAction("Index", "Pedido");
        }
        return View(checkOut);
    }

View

 @using (Html.BeginForm("CheckOut", "Carrinho", FormMethod.Post))
 {
      <button type="submit" class="btn btn-info btn-sm">
         Pagar (R$ @(@ViewBag.SubTotal + Model.PedidoAtendimentoTaxa))
      </button>

     // I need these values for Bind!!

     @*@Html.DisplayFor(m => m.IdPedidoAtendimento)
     @Html.DisplayFor(m => m.PedidoAtendimentoTaxa)
     @Html.DisplayFor(m => m.HorarioAgendado)
     @Html.DisplayFor(m => m.IdPedidoTipoPagamento)
     @Html.DisplayFor(m => m.IdUnidadeUsuario)*@

     <input asp-for="IdPedidoAtendimento" value="@Model.IdPedidoAtendimento" id="txtIdPedidoAtendimento" name="txtIdPedidoAtendimento" hidden/>
     <input asp-for="PedidoAtendimentoTaxa" value="@Model.PedidoAtendimentoTaxa" id="txtPedidoAtendimentoTaxa" name="txtPedidoAtendimentoTaxa" hidden/>
     <input asp-for="HorarioAgendado" value="@Model.HorarioAgendado" id="txtHorarioAgendado" name="txtHorarioAgendado" hidden />
     <input asp-for="IdPedidoTipoPagamento" value="@Model.IdPedidoTipoPagamento" id="txtIdPedidoTipoPagamento" name="txtIdPedidoTipoPagamento" hidden/>
     <input asp-for="IdUnidadeUsuario" value="@Model.IdUnidadeUsuario" id="txtIdUnidadeUsuario" name="txtIdUnidadeUsuario" hidden/>
  }
2
  • 1
    Can you check if the name attribute value for each input is matching with model property name? Commented Dec 23, 2019 at 16:27
  • Its ok. Thank you. Commented Dec 23, 2019 at 17:23

1 Answer 1

3

Model binding occurs based on the name attribute. You have the @Html.DisplayFor lines commented out, so it isn't binding there. For the <input> fields, you have manually entered a name of txt<PropertyName>, so it isn't binding on those, either.

ASP.NET will automatically create an appropriate name attribute just using the asp-for attribute to accommodate model binding.

Sign up to request clarification or add additional context in comments.

1 Comment

I've commented the @Html.DisplayFor because was not working, so I've tryied with <input> fields. By the way, doing what you said, that is, removing the nameattribute from <input> filds, (leting ASP.NET create automatically), works fine. Thank you for the help @nathan-miller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.