get checked check-box value using form-collection

2019-09-18 01:47发布

问题:

I have check-box input field on the view page as given below-

<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

and in the controller am getting data using form collection as given below-

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");
    }

How can I iterate only checked check-box values over there??

回答1:

Why dont you do it using htmlhelpers and models.Check this out if it might be of any help..

 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; }
  }

View will be

@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" />
}

Controller code

[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);         
         }
      }