0

Im reading a Y/N value from my model in a razor for loop.

I want to change the value from Y/N to true/false.

<td>@Html.CheckBoxFor(modelItem => (item.ReqDowngrade == "Y" ? true : false))</td>

I keep geting this error: System.InvalidOperationException: 'Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.'

Is there any way I can do this without creating a server view model?

printthis
  • 141
  • 3
  • 11
  • 1
    Send parsed data from controller . Either you can send true and false value – Asif Raza Jul 03 '18 at 18:36
  • >Is there any way I can do this without creating a server view model? it sounds like a view model is exactly what you want. – Fran Jul 03 '18 at 18:52
  • 1
    Your property needs to be `bool` to use `CheckBoxFor()` - use a view model (which should mandatory when editing data anyway) –  Jul 03 '18 at 22:02

1 Answers1

1

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>
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61