MVC Checkboxlist仅在回发中有1个项目

时间:2015-03-06 16:08:55

标签: html forms post model-view-controller checkbox

我的网站上有一个复选框列表。 Items的来源来自数据库。

@{
      dbEntities db = new dbEntities();

      foreach (var p in db.Product.ToList().OrderBy(o => o.Name))
      { 
          <input type="checkbox" name="chkProducts" class="chkclass" value="@p.ProductID" id="@p.ProductID"> @p.Name <br />
      } 
}

当我检查示例5复选框时,FormController中的结果只有一个项目在&#34; string [] chkProducts&#34;。

[HttpPost]
public ActionResult Anfrage(FormCollection collection, string[] chkProducts)
{
        var checkedItems = collection["chkProducts"]; 

为什么每次在checkedItems中只有一个项目来自5?

1 个答案:

答案 0 :(得分:1)

因为您需要使用括号[]作为输入名称:

foreach (var p in db.Product.ToList().OrderBy(o => o.Name))
      { 
          <input type="checkbox" name="chkProducts[]" class="chkclass" value="@p.ProductID" id="@p.ProductID"> @p.Name <br />
                                       // HERE-----^
      }