jeudi 21 janvier 2016

ModelState.isvalid is false when trying to save an entity, error says a field is required in a related entity

I have this code to save an entity

 public class TipoDeProducto
    {
        [Key]
        [ScaffoldColumn(false)]
        public int TipoDeProductoId{ get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "El nombre debe tener como máximo 50 caractéres")]
        public string Nombre { get; set; }

        [Required]
        public bool Estado { get; set; }

        public virtual ICollection<Producto> Productos { get; set; }
    }

and Product

 public class Producto
    {
        [Key]
        [ScaffoldColumn(false)]
        public int ProductoId { get; set; }

        public int TipoDeProductoId { get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "El nombre debe tener como máximo 50 caractéres")]
        public string NombreProducto { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        [MaxLength(300, ErrorMessage = "La descripción debe tener como máximo 300 caractéres")]
        public string Descripcion { get; set; }

        public bool Estado { get; set; }


        [ForeignKey("TipoDeProductoId")]
        public virtual TipoDeProducto TipoDeProducto { get; set; }
    }

The edit (POST) is this:

  public HttpResponseMessage PutTipoDeProducto(int id, TipoDeProducto tipoDeProducto)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != tipoDeProducto.TipoDeProductoId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            try
            {
                unitOfWork.TipoDeProductoRepository.Update(tipoDeProducto);
                unitOfWork.Save();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

My index view is like this:

@model List<PowerData.Comisiones.Models.TipoDeProducto>
    @using PowerData.Comisiones.Models
    @{
        ViewBag.Title = "Tipos de producto";
    }

    <h2>Tipos de producto</h2>

    @(Html.Kendo().Grid<TipoDeProducto>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Estado).Title("Estado");
        columns.Command(command => { command.Edit(); });
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.PopUp))

    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()
    .DataSource(dataSource => dataSource
        .WebApi()
        //.Ajax()
        //.ServerOperation(false)
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.TipoDeProductoId);
            model.Field(p => p.TipoDeProductoId).Editable(false);
        })

        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos" }))) // Action invoked when the user saves a new data item
                    .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos" }))) // Action invoked when the grid needs data
                    .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos", id = "{0}" })))  // Action invoked when the user saves an updated data item
                    .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos", id = "{0}" }))) // Action invoked when the user removes a data item

        //.Create(update => update.Action("Create", "TipoDeCanales"))
            //.Read(read => read.Action("Read", "TipoDeCanales"))
            //.Update(update => update.Action("Edit", "TipoDeCanales"))
            //.Destroy(update => update.Action("Delete", "TipoDeCanales"))
    )
    )
    <script type="text/javascript">
        function error_handler(e) {
            if (e.errors) {
                var message = "Errors:\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function () {
                            message += this + "\n";
                        });
                    }
                });
                toastr.error(message)
                //alert(message);
            }
        }
    </script>

However, after I add items, and then try to edit an existing row, the Model.Isvalid = false, and when I check the validation errors, it says ProductName is required, which is not even a field on the table I am trying to save, its a related list of entitties

Aucun commentaire:

Enregistrer un commentaire