使用表单集合检查复选框的值

时间:2016-05-02 11:41:38

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我在视图页面上有复选框输入字段,如下所示 -

<input type=@item.InputType.ToString().Trim().ToLower() id="@item.AdminAnswers.ElementAt(i).Answer" value="@item.AdminAnswers.ElementAt(i).Answer" name="@item.Id"></input>@item.AdminAnswers.ElementAt(i).Answer

并且在控制器中使用表单集合获取数据,如下所示 -

public ActionResult Index(FormCollection data)
    {
        foreach (var item in surveyDatas)
        {           
            if(item.InputType.ToString().Trim().ToLower() == "checkbox")
            {
                var dev =item.NumberOfChoice;
                for (int i = 1; i < dev; i++)
                {
                    //here I need to iterate checked checkbox value
                }
            }
            myclientanswer.DevAnswers = devAnswer;              
            clientAnswer.Add(myclientanswer);
        }
        return View("LoginResult");
    }

如何只在那里迭代检查的复选框值?

1 个答案:

答案 0 :(得分:1)

为什么不使用htmlhelpers和models来做这件事。如果可能有任何帮助,请查看它。

 public class UserModel
  {
    public List<Requirements> Requirements { get; set; }
  }
 public class Requirements
  {
    public int RId { get; set; }
    public string RName { get; set; }
    public bool RIsSelected { get; set; }
  }
 public class Pdf
  {
    public int PId { get; set; }
    public int RId { get; set; }
    public string Requirement { get; set; }
  }

查看将是

@model.usermodel
  @using (Html.BeginForm(FormMethod.Post))
    {
      @for (int i = 0; i < Model.Requirements.Count; i++)
        {
          @Html.HiddenFor(m => m.Requirements[i].RId)        
          @Html.CheckBoxFor(m => m.Requirements[i].RIsSelected, new { id = "requirements_" + i, @class = "divider" })            
          @Html.DisplayFor(m => m.Requirements[i].RName, new { @class = "divider", style = "display:inline;font-family: Courier New, Courier, monospace;" })          
        }
 <input id="Submit1" type="submit" value="submit" name="Command" />
}

控制器代码

[HttpPost]
 public ActionResult About(List<Requirements> requirements,Usermodel model)
  {
    var id = model.id;
       List<Pdf> plist = new List<Pdf>();        
        foreach (var item in requirements)
        {
          Pdf p = new Pdf();
          if (item.RIsSelected == true)
          {
           p.PId = id;
           p.RId = item.RId;
           plist.Add(p);         
         }
      }