Set a hardcoded value in a HiddenFor within a for-loop

大城市里の小女人 提交于 2019-12-13 07:58:14

问题


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
}

回答1:


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">



回答2:


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
}


来源:https://stackoverflow.com/questions/29099508/set-a-hardcoded-value-in-a-hiddenfor-within-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!