在for循环中的HiddenFor中设置硬编码值

时间:2015-03-17 12:48:51

标签: asp.net-mvc asp.net-mvc-5

当只有一个人选择时,我仍然需要将硬编码值“TRUE”分配给People [i] .IsSelected属性以满足我的验证。

我该怎么做?

@if (hasMoreThanOnePerson)
{
    <td>
        @Html.CheckBoxFor(m => m.People[i].IsSelected)
    </td>
}
else
{
    @Html.HiddenFor(m => m.People[i].IsSelected, true) // Set TRUE always to hidden field within for loop with indexer
}

2 个答案:

答案 0 :(得分:1)

使用htmlAttributes使用this overloadthis overload设置隐藏字段的value属性:

@Html.HiddenFor(m => m.People[i].IsSelected, new {Value="true"})

它将输出html,如:

<input id="YourModel.People[0].IsSelected" 
       name="YourModel.People[0].IsSelected" 
       type="hidden" 
       value="true">

答案 1 :(得分:0)

为什么不在true块内将值设置为else

@if (hasMoreThanOnePerson)
{
    <td>
        @Html.CheckBoxFor(m => m.People[i].IsSelected)
    </td>
}
else
{
    @{ Model.People[i].IsSelected = true; }
    @Html.HiddenFor(m => m.People[i].IsSelected) // Set TRUE always to hidden field within for loop with indexer
}