1

Hello everyone I have a CheckBoxFor in JavaScript and I have a field called Received that is just saving "0" or "1" in the database, so I want to display in the case that I have "1" the check as a true and "0" as a false I would like to know how to do it that is the code:


    @for (var i = 0; i < Model.PurchaseOrder.LineItems.Count(); i++)
    {
        <tr>
            <td>
            @Html.CheckBoxFor(m => m.LineItems[i].Received)
            </td>
        </tr>
    }
</table>

Model

public bool Received { get; set; }
haldo
  • 14,512
  • 5
  • 46
  • 52
Michaelweston
  • 149
  • 1
  • 11
  • that is not javascript, it's an HTMLHelper that the middleware interprets. The key to using CheckBoxFor is to create a class(viewmodel) that has a bool property = to the checked value. So in your case set "Received" property of your (lineitem?) to false for "0" and true for "1". So your viewmodel class of LineItem would have all the necessary properties along with one bool for the checkbox's checked state. (You're basically doing it right there... but you're missing the rest of the class for a LineItem.) – pcalkins Jan 13 '22 at 23:20
  • Yes you are right for some reason is always coming FALSE the values. – Michaelweston Jan 13 '22 at 23:39
  • You'll want to bind that class.. or list of class: List... then set hidden fields .HiddenFor(m => m.LineItems[i].id)... etc.. the other properties... the middleware will then create fields that map to your viewmodel. Maybe check this post for an example: https://stackoverflow.com/questions/9100169/checkboxfor-master-list-and-selected – pcalkins Jan 13 '22 at 23:42
  • Ok yes I think you are close looking the code again yes LineItem is coming from a ViewModel that contain the bool Received field public class ReveivedViewModel { public List LineItems { get; set; } } – Michaelweston Jan 13 '22 at 23:44
  • Here I had a better version if you can see it better https://stackoverflow.com/questions/70704659/checkboxfor-value-is-always-false-html-asp-net – Michaelweston Jan 14 '22 at 01:23
  • if you don't bind the class, it's going to come through as either false/false or true/false. ASP.NET does something a little weird there... it makes another hidden field that's set to false. (Has something to do with whether that item even comes through if it's binding to a data content... which you don't want... separate the data and view models... modify your DB according to returned bound view model... there's where the 0 for false 1 for true logic would come into play) – pcalkins Jan 14 '22 at 18:46

0 Answers0