开发者

Using CheckBoxFor in a loop

开发者 https://www.devze.com 2023-02-25 09:18 出处:网络
Can I useHtml.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)

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.


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>


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号