当我在mvc的ModelState中使用Ajax更新数据库时

本文关键字:Ajax 更新 数据库 mvc ModelState | 更新日期: 2023-09-27 17:58:14

当用户单击索引视图中的复选框时,我将更新数据库这是我的视图代码(视图中已将DispalyFor更改为CheckBoxFor)

@Html.CheckBoxFor(modelItem => item.Active, new
   {
       data_url = Url.Action("Subscribe", "Home"),
       data_id = item.Id,
   })

在ajax中编写这个

<script>
    $(function() {
        //var id, Active;
        $('#item_Active').change(function () {
            var ch = $(this).is(":checked");
            var data = { 'id': $(this).data('id'), 'Active': ch };
            //data[$(this).attr('name')] = $(this).is(':checked');
            $.ajax({
                url: $(this).data('url'),
                type: 'POST',
                data: data,
                success: function() {
                    alert("Ok");
                },
                error: function(e) {
                    alert(e.toString());
                }
            });
        });
    });
</script>

我的控制器在Home Action

  [HttpPost]
    public ActionResult Subscribe([Bind(Include = "id,Active")]Subscribe subscribe)
    {
        if (ModelState.IsValid)
        {
            var sub = db.Subscribes.FirstOrDefault(x => x.Id == subscribe.Id);
           db.Entry(subscribe).State = EntityState.Modified;
                db.SaveChanges();
           }
        return RedirectToAction("Index");
    }

当点击我的复选框得到这个错误

System.InvalidOperationException: Attaching an entity of type '' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

当我在mvc的ModelState中使用Ajax更新数据库时

从DB加载实体时,EF会跟踪该实体的任何更改。问题是,您想让EF跟踪该类型的另一个实例(在您的案例中为subscribe),其Id与旧实例(在我们的案例中是sub)完全相同。

由于EF通过对象的Id来识别对象,因此不能有两个具有相同Id的类型实例。因此,一种可能的方法是修改旧的方法:

var sub = db.Subscribes.FirstOrDefault(x => x.Id == subscribe.Id);
sub.Active = subscribe.Active;
db.SaveChanges();