Rob Rob - 1 year ago 56
C# Question

Error 'cannot convert from bool to list<bool> when using checkboxfor in a for loop that is within another for loop?

I am trying to create a quiz, the quiz has questions that require a single answer and questions that require multiple answers to be selected. For the questions that require multiple answers to be selected I am using the Checkboxfor helper. I'll shorten all my code for the sake of the question. I have a viewmodel which is sent to the page:

public class QuizViewModel
public int QuizQuestionID { get; set; }
public int QuizID { get; set; }
public int EnrollmentID { get; set; }
public int OldCoursePageID { get; set; }
public string Question { get; set; }
public int Order { get; set; }
public int Type { get; set; }
public string SelectedAnswer { get; set; }
public IList<QuizAnswers> QuizAnswers { get; set; }


The model QuizAnswers which is used in the viewModel:

public class QuizAnswers
public int QuizAnsID { get; set; }
public int QuizQuestionID { get; set; }
public string Answer { get; set; }
public int Order { get; set; }
public bool Correct { get; set; }

public virtual QuizQuestions QuizQuestions { get; set; }


In my view I have a loop for the questions and then for the answers:

for (var i = 0; i < Model.Count(); i++)
if (Model[i].Type == 2)
for (int k = 0; k < Model[i].QuizAnswers.Count(); k++)
@Html.CheckBoxFor(Model[i].QuizAnswers[k].Correct, new { value = false, id = "checkanswer", data_questionid = @Model[i].Order })
@Html.DisplayFor(model => Model[i].QuizAnswers[k].Answer)

I am receiving the error on the checkboxfor helper. I was planning on creating a field for the boolean returned by the checkbox, however I just tested to see if I could create the helper and populate the already existing Correct boolean field with the checkbox boolean and ran into this problem.

As far as I can see:


Should provide a single bool to populate not a list. Where am I going wrong?

Answer Source

You're missing the model => part of your Html.CheckBoxFor. If you add that like you have in your @Html.DisplayFor it should take the error away

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download