Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Edit method posting null entity.

$
0
0

Hey guys!

I'm working in an ASP.NET Core app, and it was working perfectly, however when it comes to the update part I get a Null Exception error when posting. And when debugging I can see that it is posting everything as either Null for the entities and 0 for the values.

Edit GET/POST Methods:

        public async Task<IActionResult> Edit(int? id)
        {
            ClientViewModel updateClient = new ClientViewModel() ;
            updateClient.Intereses = ListaIntereses();

            if (id == null)
            {
                return NotFound();
            }

            var cliente = await _context.Clientes.SingleOrDefaultAsync(m => m.ID == id);
            if (cliente == null)
            {
                return NotFound();
            }

            UpdateViewModel actualizarCliente = new UpdateViewModel
            {
                NumeroTarjeta = cliente.NumeroTarjeta,
                Nombre = cliente.Nombre,
                Apellido = cliente.Apellido,
                TelefonoCelular = cliente.TelefonoCelular
            };

            updateClient.Cliente = actualizarCliente;
           
            return View(updateClient);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, ClientViewModel cliente)
        {
            var tienda = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Country)?.Value;
            if (tienda == null){
                return RedirectToAction("Prohibido", "Usuario");
            }
            else
            {        
                if (ModelState.IsValid)
                {
                    try
                    {
                        _context.Update(cliente.Cliente);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!ClienteExists(cliente.Cliente.ID))
                        {
                            return NotFound();
                        }
                        else
                        {
                            throw;
                        }
                    }
                    return RedirectToAction("Index");
                }
                return View(cliente.Cliente);
            }
        }

ViewModels and Model:

    public class ClientViewModel
    {
        public UpdateViewModel Cliente { get; set; }
        public List<Interes> Intereses { get; set; }
        public List<int> InteresSeleccionado { get; set; }

        public ClientViewModel()
        {
            Intereses = new List<Interes>();
            InteresSeleccionado = new List<int>();
        }

    }

    public class UpdateViewModel
    {
        public int ID { get; set; }

        public int NumeroTarjeta { get; set; }
        [Required]
        [Display(Name = "Identificación")]
        public string Identificacion { get; set; }
        public string Nombre { get; set; }
        public string Apellido { get; set; }
        [Required]
        public string Genero { get; set; }
        public string TelefonoCelular { get; set; }
        [Display(Name = "Correo Electrónico")]
        [Required]
        [EmailAddress(ErrorMessage = "El correo eletrónico no es válido.")]
        public string CorreoElectronico { get; set; }
        [Required]
        public DateTime FechaNacimiento { get; set; }

        ///PROPIEDAD PARA LAS PROVINCIAS
        public string Provincia { get; set; }
        public virtual ICollection<ClienteInteres> ClienteInteres { get; set; }
    }

And finally the Edit View:

@model Models.ViewModels.UpdateViewModel

@{
    ViewData["Title"] = "Edit";
}<h2>Edit</h2><form asp-action="Edit"><div class="form-horizontal"><h4>ActualizarClienteViewModel</h4><hr /><div asp-validation-summary="ModelOnly" class="text-danger"></div><input type="hidden" asp-for="ID" /><div class="form-group"><label asp-for="NumeroTarjeta" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="NumeroTarjeta" class="form-control" /><span asp-validation-for="NumeroTarjeta" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Identificacion" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Identificacion" class="form-control" /><span asp-validation-for="Identificacion" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Nombre" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Nombre" class="form-control" /><span asp-validation-for="Nombre" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Apellido" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Apellido" class="form-control" /><span asp-validation-for="Apellido" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Genero" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Genero" class="form-control" /><span asp-validation-for="Genero" class="text-danger"></span></div></div><div class="form-group"><label asp-for="TelefonoCelular" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="TelefonoCelular" class="form-control" /><span asp-validation-for="TelefonoCelular" class="text-danger"></span></div></div><div class="form-group"><label asp-for="CorreoElectronico" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="CorreoElectronico" class="form-control" /><span asp-validation-for="CorreoElectronico" class="text-danger"></span></div></div><div class="form-group"><label asp-for="FechaNacimiento" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="FechaNacimiento" class="form-control" /><span asp-validation-for="FechaNacimiento" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Provincia" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Provincia" class="form-control" /><span asp-validation-for="Provincia" class="text-danger"></span></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div></div></div></form><div><a asp-action="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

EDIT:

Error I'm getting

ArgumentNullException: Value cannot be null.

Microsoft.EntityFrameworkCore.Utilities.Check.NotNull<T>(T value, string parameterName)

Entity:
Microsoft.EntityFrameworkCore.Utilities.Check.NotNull<T>(T value, string parameterName)
Microsoft.EntityFrameworkCore.DbContext.Update<TEntity>(TEntity entity)

Hopefully I can get some insight on what's wrong! Because I've tried a lot of things and can't get it to work.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>