c# - 尝试保存实体时 ModelState.isvalid 为 false,错误表示相关实体中需要一个字段

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-3

我有这个代码来保存实体

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

我的索引 View 是这样的:

@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 是必需的,这甚至不是我表中的字段我正在尝试保存,它是一个相关的实体列表

最佳答案

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

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

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

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

关于c# - 尝试保存实体时 ModelState.isvalid 为 false,错误表示相关实体中需要一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933834/

相关文章:

c# - 办公室 365 API : Add a contact to an organisation distribution list

c# - 使具体的返回类型通用

c# - 在 ASP.NET Core 中访问 _Layout.cshtml 中的 cookie

c# - FindAsync 返回最近的 1000 个结果

asp.net-mvc - 如何将现有 MVC3 应用程序的开发转变为 TDD 方法?

c# - 如何显示目录中的文件

c# - 在 .NET 4.6 项目中引用 .NET Core 库

javascript - 同心圆中心的 Canvas 文本

c# - Modal PopUp Extender 中的 GridView ?

c# - 使用 IEnumerable.Select 过滤记录