How to insert data from a form into a sql database

I have a form page that has data on it that I need to insert into a sql database. When the submit button is clicked. I have the basics coded but i get the following error when I click the sumbit button:

Error submitting form: Value cannot be null. (Parameter 'client')

here is the pages code:

type or paste code here
@page "/summary"
@attribute [Authorize]
@using System.Text.Json;
@inject IJSRuntime _js
@inject NavigationManager NavigationManager
@inject DialogService DialogService
@inject ContextMenuService ContextMenuService
@inject TooltipService TooltipService
@inject NotificationService NotificationService
@inject IJSRuntime JSRuntime
@using Blazored.LocalStorage
@inject HttpClient Http


<PageTitle>Summary</PageTitle>

<RadzenGrid Data="@filteredSessionData" TItem="FormData">
    <Columns>
        <RadzenGridColumn TItem="FormData" Property="BuildingName" Title="School" />
        <RadzenGridColumn TItem="FormData" Property="CPSNumber" Title="CPS Number" />
        <RadzenGridColumn TItem="FormData" Property="Description" Title="Item Description" />
        <RadzenGridColumn TItem="FormData" Property="ReasonDescription" Title="Reason For Surplus" />
        <RadzenGridColumn TItem="FormData" Property="Edit">
            <Template Context="data">
                <div style="text-align: center;">
                    <RadzenButton Icon="edit" Style="background-color: #005570;" Click="() => EditItem(data)"></RadzenButton>
                </div>
            </Template>
        </RadzenGridColumn>
    </Columns>
</RadzenGrid>

<RadzenButton Style="width: 100%; min-width: 0px; min-height: 0px; height: 40px; display: block; background-color: #005570" Text="Submit" Click="SubmitForm"></RadzenButton>

<div class="back-button">
    <RadzenButton Icon="print" Style="background-color: #005570; float: left; vertical-align: text-top; text-align: center" Click="PrintMe"></RadzenButton>
</div>

@code {
    // Define the FormData class if it's not already defined
    public class FormData
    {
        public string BuildingName { get; set; }
        public string CPSNumber { get; set; }
        public string Description { get; set; }
        public string ReasonDescription { get; set; }
    }

    // Read the stored local storage data
    private List<FormData> sessionData = new List<FormData>();

    // Filtered session data without null CPSNumber
    private List<FormData> filteredSessionData = new List<FormData>();

    // Inject the ILocalStorageService
    [Inject]
    private ILocalStorageService localStorage { get; set; }

    [Inject]
    protected SecurityService Security { get; set; }

    protected override async Task OnInitializedAsync()
    {
        // Load the data from local storage
        try
        {
            sessionData = await localStorage.GetItemAsync<List<FormData>>("inputCardData");

            // Filter out rows with null CPSNumber
            filteredSessionData = sessionData.Where(row => !string.IsNullOrEmpty(row.CPSNumber)).ToList();

            // Set the same BuildingName for all rows
            if (filteredSessionData.Count > 0)
            {
                var buildingName = filteredSessionData[0].BuildingName;
                filteredSessionData.ForEach(row => row.BuildingName = buildingName);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading from local storage: {ex.Message}");
        }
    }

    private void EditItem(FormData data)
    {
        NavigationManager.NavigateTo("/SuccessPage"); // Replace with the actual Razor page URL
    }

  private async Task SubmitForm()
    {
        try
        {
            var formData = filteredSessionData.FirstOrDefault();

            var surplusItem = new
            {
                BuildingName = formData.BuildingName,
                CPSNumber = formData.CPSNumber,
                Description = formData.Description,
                ReasonDescription = formData.ReasonDescription
            };

            var response = await Http.PostAsJsonAsync("/api/surplusitems", surplusItem); // Use relative path

            if (response.IsSuccessStatusCode)
            {
                await localStorage.RemoveItemAsync("inputCardData");
                NavigationManager.NavigateTo("/success");
            }
            else
            {
                Console.WriteLine($"Error inserting data into the database. Status code: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error submitting form: {ex.Message}");
        }
    }


    private async Task PrintMe()
        => await _js.InvokeVoidAsync("window.print");
}

<style>
    .back-button {
        position: fixed;
        bottom: 20px;
        right: 20px;
    }

    .back-button a {
        display: inline-block;
        background-color: #005570;
        color: white;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        text-decoration: none;
    }

    .back-icon {
        font-size: 20px;
    }
</style>

here is the api cs code:

// SurplusItemsController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class SurplusItemsController : ControllerBase
{
private readonly YourDbContext _context;

public SurplusItemsController(YourDbContext context)
{
    _context = context;
}

[HttpPost]
public async Task<IActionResult> PostSurplusItem([FromBody] SurplusItemDto surplusItemDto)
{
    try
    {
        // Create a SurplusItem entity from the DTO
        var surplusItem = new SurplusItem
        {
            BuildingName = surplusItemDto.BuildingName,
            CPSNumber = surplusItemDto.CPSNumber,
            Description = surplusItemDto.Description,
            ReasonDescription = surplusItemDto.ReasonDescription
        };

        // Set SurplusStatus to 0
        surplusItem.SurplusStatus = 0;

        // Add the entity to the context
        _context.SurplusItems.Add(surplusItem);

        // Save changes to the database
        await _context.SaveChangesAsync();

        return Ok();
    }
    catch (Exception ex)
    {
        // Log the exception
        return StatusCode(500, "Internal server error");
    }
}}

I am still new to razor page app development so any suggestions would be great or if I am going in the wrong direction please let me know

thanks in advance!!!

Hi @Christopher_DeBrodie,

You might need to try Radzen Blazor Studio with some CRUD pages just to check what code is generated.

thank you very much for the reply I looked into your suggestion but everything I have seen with CRUD pages allows you to edit within the data grid. I need the data to be inserted into the database when a submit button is clicked not in real time can you please assist with how to go about do that with CRUD pages?

Thanks in advance!

Well, CRUD pages generated by Radzen Blazor Studio are far more than "editing in the DataGrid". They are actually three separate pages (Add, Edit and main page with the DataGrid). All pages are connected to a service which is using Entity Framework DbContext to perform all database operations.