Set a hardcoded value in a HiddenFor within a for-

2019-09-20 04:39发布

When there is only one person to select I still need to assign the hardcoded value 'TRUE' to the People[i].IsSelected property to satisfy my validation.

How can I do that?

@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条回答
狗以群分
2楼-- · 2019-09-20 05:02

Use htmlAttributes to set value property of Hidden Field using this overload or this overload:

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

It will output html like:

<input id="YourModel.People[0].IsSelected" 
       name="YourModel.People[0].IsSelected" 
       type="hidden" 
       value="true">
查看更多
Rolldiameter
3楼-- · 2019-09-20 05:07

Why not just set the value to true inside the else block?

@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
}
查看更多
登录 后发表回答