在它到达之前离开循环并且没有错误

时间:2016-03-29 00:46:48

标签: asp.net-mvc c#-4.0

你好我有一个包含复选框和jquery的列表我得到了检查项目ID并在数组中收集它们但我的循环在所有项目检查之前结束。这是控制器;

这里是从Url获​​取Array;

public class IntArrayModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
            {
                return null;
            }

            return value
                .AttemptedValue
                .Split(';')
                .Select(int.Parse)
                .ToArray();
        }
    }

public ActionResult ApproveSelected([ModelBinder(typeof(IntArrayModelBinder))] int[] id)
    {

        try
        {

            var AllParticipants = Db.Participants
            .Where(m => id.Contains(m.Id))
            .OrderBy(m => m.Id)
            .ToList();

            for (int i = 0; i < AllParticipants.Count; i++)
            {

                var item = AllParticipants.First();
                item.Approval = true;

                var itemRemove = AllParticipants.First();
                AllParticipants.Remove(item);

            }

            Db.SaveChanges();
        }
        catch
        {
            return Json(new { IsComplete = false });
        }

        return Json(new { IsComplete = true });
    }

所以如果我发送1 Id没问题。如果我发送2如果第一个的更改批准然后离开循环成功消息。如果我发送2,则更改2然后离开1.当我转到4时它改变2并且当我转到5时离开2它改变3并且离开2.它很尴尬。我该如何解决?

1 个答案:

答案 0 :(得分:0)

更改

for (int i = 0; i < AllParticipants.Count; i++)
        {

            var item = AllParticipants.First();
            item.Approval = true;

            var itemRemove = AllParticipants.First();
            AllParticipants.Remove(item);

        }

对此:

Db.Participants
  .Where(m => id.Contains(m.Id))
  .ToList()
  .ForEach(participant=>participant.Approval=true);

Db.SaveChanges();