Luis Valencia
Luis Valencia

Reputation: 34028

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

Upvotes: 2

Views: 1637

Answers (2)

Sean
Sean

Reputation: 15164

This is what I do to ensure the validation applies to the current entity only:

        foreach (var key in ModelState.Keys)
            if (key.Split('.').Length > 2)
                ModelState[key].Errors.Clear();

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

The check for the number of occurrences of . means: if the modelstate key is something like currentDTO.relatedDTO.field then that validation error is ignored (cleared). If it's just something like id or currentDTO.validateThisField, then it doesn't get cleared.

Upvotes: 2

Rahul
Rahul

Reputation: 77896

probably default model binder is trying to bind the related entity productos as well. You can override that using the Bind attribute ([Bind(Exclude="")]) like

  public HttpResponseMessage PutTipoDeProducto(int id, [Bind(Exclude="productos")]TipoDeProducto tipoDeProducto)
   {
         //code here
   }

Upvotes: 1

Related Questions