Search code examples
c#databaseblazorentitytwo-way

Blazor & Entity Framework Two-Way-Binding


I have an application written in Blazor Server .Net6. The reason of using Blazor Server instead of WebAssembly is because the site is holding database connections. On one of the pages has a table with many rows where the last column is an input with type of checkbox. In addition it's row has an ID in case is needed.

enter image description here

I am trying to archive two way binding, so when a checkbox is set to true, database record should be updated and the corresponding row/column change the value to True.

Can this be done in elegant way, like old school DevExpress or Telerik was doing on WPF with binding without events using ObservableCollections, or is needed to create event functions and post methods and LinQ to archive this?

View Code:

<tbody>
   @foreach (var datamodel_structure in datamodel_structureList)
   {
       <tr>
           <td><input type="checkbox" @bind=datamodel_structure.datamodel_structure_is_selected /></td>
       </tr>
   }
</tbody>

Controller Code:

[HttpGet, Route("structure/{id:int}")]
public async Task<List<DataModel_Structure_Ind>> GetDataModel_Structures(int id)
{
   return await Task.FromResult(_IDataModel.GetDataModel_Structures(id));
}

Interface Code:

public List<DataModel_Structure_Ind> GetDataModel_Structures(int id);

Service Code:

public List<DataModel_Structure_Ind> GetDataModel_Structures(int id)
{
    try
    {
        return _dbContext.DataModel_Structures_Ind
            .OrderBy(x => x.datamodel_structure_id)
            .Where(x => x.datamodel_id == id)
            .ToList();
    }
    catch
    {
        return null;
    }
}

Solution

  • What if you made a custom checkbox component that takes the FieldName/ID as a Key and then has the Value that would reflect what the UI depicts and what the server has? The checkbox onchange event could fire off a SQL CMD to update, then after the DB has been updated you can call StateHasChanged() in the custom checkbox component to update the UI to reflect the changes.