当用户单击索引视图中的复选框时,我将更新数据库,这是我的查看代码(在视图中将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>
而我的控制器处于“家庭动作”中
[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.
从数据库加载实体时,EF会跟踪该实体的所有更改。问题是您想让EF跟踪该类型的另一个实例(subscribe
在您的情况下),而该实例与Id
旧实例完全相同(sub
在您的情况下)。
由于EF通过其Id
s识别对象,因此不能有两个具有相同类型的实例Id
。因此,一种可能的方法是只修改旧的方法:
var sub = db.Subscribes.FirstOrDefault(x => x.Id == subscribe.Id);
sub.Active = subscribe.Active;
db.SaveChanges();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句