0

Can I use Html.CheckBoxFor in a loop? If so how?

Here is an example of what I am trying to do. (This is using spark, but the question still applies to razor or aspx)

<ul class="voteOptions">
    <for each="var answer in poll.Answers">
        <li>!{Html.LabelFor(a =>a.Answer)}</li>
        <li>!{Html.CheckBoxFor(a =>a.Key)}</li>
    </for>
 </ul>

This obviously doesn't work because a represents the viewmodel not the current item in the loop.

2
  • Are you encountering some problems with this? If yes could you describe them in more details? Commented Apr 13, 2011 at 8:58
  • possible duplicate of How to use EditorFor inside a foreach Commented Apr 13, 2011 at 13:48

2 Answers 2

3

You could try this:

<for each="var answer in poll.Answers">
    <li>!{Html.LabelFor(a => answer.Answer)}</li>
    <li>!{Html.CheckBoxFor(a => answe.Key)}</li>
</for>

But obviously a better solution is to never write any loops but use editor templates as in this case your code will become:

<ul class="voteOptions">
    !{Html.EditorFor(x => x.Answers)}
</ul>
Sign up to request clarification or add additional context in comments.

2 Comments

I take your point for the regarding editor template. How is the first part of your answer different to mine?
@Dan, a => answer.Answer where answer is the variable you have defined in the loop. Not sure if it is the proper syntax though as I am not familiar with Spark.
0

I don't like doing it this way, but it works if you have to use Html.XXXFor

1: Create a property on your model called CurrentAnswer (type Answer)

2: In your loop set answer to CurrentAnswer

3: then call Html.XXXFor(a => a.CurrentAnswer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.