0
votes

Input tag helpers require checkboxes to be bound to non-nullable boolean fields yet my legacy sql tables contain nullable tinyint fields. Existing data is 1, 0 or Null. Entity Framework generates nullable byte? properties for those fields in the model. My razor page is bound directly to the generated database model. Now I want to bind checkboxes to those fields. What options are available? Changing the database is not possible.

Should I make matching bound boolean properties in the razor page model? In the get/set I could pull/push converted values to the database model's byte? fields. In the past (using non-razor MVC) I've bound my page to a viewmodel with the generated model hanging off of it in a property. That allowed me to bind to the viewmodel and "fix" data issues in the controller.

I'll try that idea but I'm wondering if I'm heading down the wrong path?

EDIT: I found a solution which I'll post as an answer. My original idea (above) failed (coding in property get/set) because the database model was null at that time. Instead I pull/push values in the OnGet and OnPost routines. Still I'm not sure if the is the preferred way to solve the problem.

1

1 Answers

0
votes

To update a nullable byte field named OnChart in the database model:

 public byte? OnChart { get; set; }

Create a corresponding bound boolean field in the page model:

 [BindProperty]
 public bool OnChartBoolean { get; set; }

In the razor page bind to the bool property:

<input asp-for="OnChartBoolean" type="checkbox" class="form-check-input" >

You can then convert and move the data from the byte? field to the bool (and back) in the OnGet and OnPost routines. In the OnGet routine:

        if (myTable.OnChart == null || myTable.OnChart == 0)
        {
            OnChartBoolean = false;
        }
        else 
        {
            OnChartBoolean = true;
        }

Then in the OnPost routine:

    if (OnChartBoolean == false)
    {
        myTable.OnChart = 0;
    }
    else
    {
        myTable.OnChart = 1;
    }