C#foreach循环在迭代过程中跳过一些值

问题描述 投票:-2回答:1

我有一个多选控件,因此我需要将所有选择的项提交到SQL Server表中。当我提交表单时,即使我使用Step Debugger进行检查,也只有一项得到落实,所有选择的值的确确实填充在变量employeees4中(附加图像)。我观察到,只有选择中的第一项已提交。对我可能会缺少的任何帮助吗?

[请注意,我在所附的图像中使用了略有不同的变量名,即year而不是employeees4,但是代码是相同的。

我正在选择以下项目:

     [HttpPost]
    public ActionResult NewOverTimeRequest(FormCollection formcollection)
    {

        Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
         try
        {

            var batch = new OvertimeBatch();
            request.employees = GetEmployees();

            request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
            var employeees1= request.EmployeeNumber.Split(',');                
            string[] employeees2 = employeees.SingleOrDefault().ToArray();
            string employeees3 = Helpers.ConvertStringArrayToString( employeees2);
            string[] employeees4 =employeees3.Split(new char[] { ',' });
            if (ModelState.IsValid)
            {
                foreach ( string emp in employeees4)
                {
                    using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
                    {

                        SqlCommand cmd = new SqlCommand("SubmitOverTime", conn);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@EmpNum", emp);
                        cmd.Parameters.AddWithValue("@DateDone", DateTime.Now);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }

                }
                  return RedirectToAction("OverTime");
            }
            catch (Exception ex)
        {
            ViewBag.ErrorMessage = ex.Message;
            return View(request);
        }

        return RedirectToAction("OverTime");

       }
}

型号:

    [Required]
    [Display(Name = "Employee ")]
    public string[] EmployeeNumber { get; set; }
    public Employee Employee { get; set; }
    public String DisplayName { get; set; }
    public IEnumerable<SelectListItem> employees { get; set; }

StepDebugger

sql arrays string multi-select
1个回答
1
投票

尝试将您的条件更改为以下条件。

if (ModelState.IsValid)
{
    using(SqlConnection conn = New SqlConnection(Helpers.DatabaseConnect))
    {
        conn.Open();
        SqlCommand cmd = New SqlCommand("SubmitOverTime", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@EmpNum", SqlDbType.varchar(max));
        cmd.Parameters.Add("@DateDone", SqlDbType.DateTime);
        foreach(String emp In employeees4)
        {
           cmd.Parameters["@FixtureId"].Value=emp;
           cmd.Parameters["@FixtureId"].Value= DateTime.Now;
           cmd.ExecuteNonQuery();
        }
    }

    return RedirectToAction("OverTime");
}
© www.soinside.com 2019 - 2024. All rights reserved.