模型状态.isvalid在尝试保存实体时为假,错误表示相关实体中需要字段

本文关键字:实体 表示 错误 字段 isvalid 状态 模型 保存 | 更新日期: 2023-09-27 18:31:31

我有这段代码来保存实体

 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; }
    }

和产品

 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; }
    }

编辑 (POST) 是这样的:

  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);
        }

我的索引视图是这样的:

@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>

但是,在我添加项目后,然后尝试编辑现有行,Model.Isvalid = false,当我检查验证错误时,它说 ProductName 是必需的,这甚至不是我尝试保存的表上的字段,它是一个相关的目录列表

模型状态.isvalid在尝试保存实体时为假,错误表示相关实体中需要字段

这是我为确保验证仅适用于当前实体所做的:

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

检查.的出现次数意味着:如果模型状态键类似于currentDTO.relatedDTO.field则忽略(清除)该验证错误。如果它只是像 idcurrentDTO.validateThisField ,那么它不会被清除。

可能默认模型绑定器也在尝试绑定相关实体productos。您可以使用 Bind 属性 ( [Bind(Exclude="")] ) 覆盖它,例如

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