I have the following create page in a Blazor app and I am trying to get it to add an entry to the database. In theory the create page should allow you to add a watchlist which has a name, an ID and the user ID as a foreign key.
watchlists/create:
@page "/watchlists/create"
@using Microsoft.EntityFrameworkCore
@using RookSecurities.com.Models
@using System.Security.Claims
@using Microsoft.AspNetCore.Authorization
@inject IDbContextFactory DbFactory
@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider Auth
@attribute [Authorize]
Create
Create
Watchlist
@code {
[SupplyParameterFromForm]
private Watchlist Watchlist { get; set; } = new();
// To protect from overposting attacks, see https://learn.microsoft.com/aspnet/core/blazor/forms/#mitigate-overposting-attacks.
private async Task AddWatchlist()
{
var authState = await Auth.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity?.IsAuthenticated == true)
{
var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId != null)
{
Watchlist.UserId = userId; // Set here, NOT in form
await using var db = await DbFactory.CreateDbContextAsync();
db.Watchlist.Add(Watchlist);
await db.SaveChangesAsync();
Watchlist = new(); // Reset
}
}
}
}
The watchlist model:
using RookSecurities.com.Data;
using System.ComponentModel.DataAnnotations;
namespace RookSecurities.com.Models
{
public class Watchlist
{
[Required]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
public string Name { get; set; }
public ApplicationUser User { get; set; } = null!;
public List Symbols { get; set; } = new();
}
}
I am getting an error stating:
InvalidOperationException: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.
However looking at the edit form code it appears that it has a model set:
What do I need to add to get this database call to work?