@ Html.CheckBoxFor与for循环中的字符串

时间:2019-04-09 20:30:15

标签: c# asp.net-mvc razor

我正在用MVC构建动态表格。所有(约50个)问题和提供的答案都存储在数据库中。 我使用for循环用问题动态填充视图,这对于@HtmlEditorFor效果很好,但不适用于需要使用复选框的地方。由于形式是动态的,因此答案属性始终是字符串。我想将0或1作为答案存储在checkbox-questions数据库中。 对于@HtmlCheckBoxFor,我收到一条错误消息:

  

“模板只能与字段访问,属性访问,一维数组索引或单参数自定义索引器表达式一起使用。”

模板只能与字段访问,属性访问,一维数组索引或单参数自定义索引器表达式一起使用。

@for (int i = startValue; i < maxValue; i++) {

<tr>
<td>@Html.DisplayFor(r => r.Questions[i].QuestionText)</td>

<td>@Html.CheckBoxFor(r => r.Questions[i].Answer == "1")</td>

</tr>
startValue++;
}

1 个答案:

答案 0 :(得分:0)

要解决此问题,请尝试减少QuestionText的长度  :

@for (int i = startValue; i < maxValue; i++) {

<tr>
<td>@Html.DisplayFor(r => r.Questions[i].QuestionText.Substring(0,100) )</td>

<td>@Html.CheckBoxFor(r => r.Questions[i].Answer == "1")</td>

</tr>
startValue++;
}

或者您可以使用以下解决方案解决您的问题:

   @for (int i = startValue; i < maxValue; i++) {

    <tr>
    <td> @Questions[i].QuestionText </td>

    <td>@Html.CheckBoxFor(r => r.Questions[i].Answer == "1")</td>

    </tr>
    startValue++;
    }

我希望此解决方案可以为您提供帮助

相关问题