创建动态文本框列表并将其返回到通过控制器查看

时间:2017-01-26 15:30:09

标签: c# jquery asp.net

我试图循环使用jquery动态创建的特定文本框。现在在formcollection中,我想从控制器中循环检索这些值作为sting列表并将该列表返回到视图。

foreach(string item in form.Keys){
   if (actCount > 1)
   {
       for (int i = 1; i < actCount; i++)
       {
           if (frm["AccountNumberTextBox" + i].Substring(0, 3) != "165")
           {   
                ViewBag.SaveError = "";
                ViewBag.SaveError = "Invalid customer account number detected. Account number must start with 165 but not " + frm["txtAccountNumberField" + i].Substring(0, 3);

                ViewBag.ValidationStatus = false;

                Response.Write(frm["AccountNumberTextBox" + i]);
                lst.Add(frm["AccountNumberTextBox" + i]);

                ViewBag.ListOfAccounts = lst;
                this.redisplay();

                return View(customerModel);
            }
        }
    }
}

当我运行代码时,我在视图中出现错误,如下所示

for (int i = 1; i < accountsTotal; i++)
{
    foreach (var item in ViewBag.ListOfAccounts)
    {
    }
}

enter image description here

如果提出解决方案或建议,我将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试以下。 你应该把你的return语句放在for循环

之外
foreach(string item in form.Keys){
   if (actCount > 1)
   {
       for (int i = 1; i < actCount; i++)
       {
           if (frm["AccountNumberTextBox" + i].Substring(0, 3) != "165")
           {   

                ViewBag.SaveError = "Invalid customer account number detected. Account number must start with 165 but not " + frm["txtAccountNumberField" + i].Substring(0, 3);

                ViewBag.ValidationStatus = false;


                lst.Add(frm["AccountNumberTextBox" + i]);

                ViewBag.ListOfAccounts = lst;
                this.redisplay();


            }
        }
    }
}
return View(customerModel);

同时确保以下条件按预期正常工作

if (frm["AccountNumberTextBox" + i].Substring(0, 3) != "165")

在您的视图中,而不是直接从ViewBag访问项目,而不是在变量

中访问项目
    @{
    @*I assume you want all items as string *@
    var list = ViewBag.ListOfAccounts != null ? (List<string>)ViewBag.ListOfAccounts : new List<string>();

}

并使用此变量list来迭代for循环