This declaration is totally wrong:
@Html.CheckBoxFor(modelItem => (item.ReqDowngrade == "Y" ? true : false))
CheckBoxFor
helper only accepts viewmodel properties with either bool
or Nullable<bool>
type for model binding, hence the conditional expression above should not be used. If you want to assign Y
or N
value to a new bool viewmodel property bound with CheckBoxFor
, do this instead:
Viewmodel
// assumed both 'ReqDownGrade' & new bool property are in same viewmodel class
public bool CheckReqDownGrade
{
get
{
// returns false if ReqDownGrade is 'N'
return (ReqDownGrade == "Y");
}
set
{
CheckReqDownGrade = value;
CheckReqDownGrade == true ? ReqDownGrade = "Y" : ReqDownGrade = "N";
}
}
View
@Html.CheckBoxFor(model => model.CheckReqDownGrade)
If you still insist to not adding bool
viewmodel property, you can use a HiddenFor
, standard HTML input
element with type="checkbox"
attribute and simple JS trick:
View
@Html.HiddenFor(modelItem => item.ReqDowngrade, new { id = "ReqDownGrade" })
<input id="CheckReqDownGrade" type="checkbox" @(item.ReqDowngrade == "Y" ? "checked='checked'" : "") />
JS (jQuery)
<script>
$(function() {
$('#CheckReqDownGrade').click(function() {
var isChecked = $(this).is(':checked');
$('#ReqDownGrade').val(isChecked ? 'Y' : 'N');
});
});
</script>