skip to Main Content

I’m currently building a Create Account page for my project and trying to figure out what’s wrong with my code. The issue is that, when I fill in all the blanks and press the Create Account button it sends empty values. I have no idea why is that.. I hope someone here will help me. Thanks!

@page "/CreateAccount"

@using System.Net.Http
@using System.Net.Http.Json
@using WebApp.Models

@inject IHttpClientFactory HttpClientFactory
@inject NavigationManager NavigationManager

<PageTitle>Create Account</PageTitle>

<div class="d-flex justify-content-center align-items-center vh-100 bg-dark text-white">
    <EditForm Model="@user" OnValidSubmit="RegisterAccount" class="text-center w-25" FormName="CreateAccount">
        <h1 class="mb-5">Create an Account</h1>

        <div class="form-group">
            <label for="name">Name</label>
            <InputText id="name" @bind-Value="user.Name" class="form-control" />
        </div>

        <div class="form-group">
            <label for="email">Email</label>
            <InputText id="email" @bind-Value="user.Email" class="form-control" />
        </div>

        <div class="form-group">
            <label for="password">Password</label>
            <InputText id="password" @bind-Value="user.Password" type="password" class="form-control" />
        </div> 

        <button type="submit" class="btn btn-primary mt-4">Create Account</button>
    </EditForm>
</div>

@code {
    private AccountDetails user = new AccountDetails();

    private async Task RegisterAccount()
    {
        Console.WriteLine($"Email: {user.Email}");
        Console.WriteLine($"Username: {user.Name}");
        Console.WriteLine($"Password: {user.Password}");

        var httpClient = HttpClientFactory.CreateClient("ApiClient");
        var response = await httpClient.PostAsJsonAsync("api/AccountDetails", user);
            
            if (response.IsSuccessStatusCode)
            {
                NavigationManager.NavigateTo("/HomeManager");
            }
            else
            {
                Console.WriteLine("Error: " + response.ReasonPhrase);
            }
        }
    }
}

Model

using System.ComponentModel.DataAnnotations;

namespace WebApp.Models
{
    public class AccountDetails
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Invalid email address")]
        public string Email { get; set; } = string.Empty;

        [Required(ErrorMessage = "Username is required")]
        public string Name { get; set; } = string.Empty;

        [Required(ErrorMessage = "Password is required")]
        [MinLength(6, ErrorMessage = "Password must be at least 6 characters long")]
        public string Password { get; set; } = string.Empty;

        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }
}

API

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApp.Data;
using WebApp.Models;
using System.Threading.Tasks;

namespace WebApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AccountDetailsController : ControllerBase
    {
        private readonly AccountDetailsContext _context;

        public AccountDetailsController(AccountDetailsContext context)
        {
            _context = context;
        }

        [HttpPost]
        public async Task<IActionResult> PostAccountDetails([FromBody] AccountDetails accountDetails)
        {
            if (accountDetails == null)
            {
                Console.WriteLine("Received null data.");
                return BadRequest("Invalid data.");
            }

            Console.WriteLine($"Received data: Name={accountDetails.Name}, Email={accountDetails.Email}, Password={accountDetails.Password}");

            try
            {
                _context.AccountDetails.Add(accountDetails);
                await _context.SaveChangesAsync();
                return Ok();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }
    }
}

I’ve tried HTTP Post method directly in Visual Studio by REST Client extension and the data are saved fine into database. Only, when the user enters the values in the form it sends empty values

POST http://localhost:5237/api/AccountDetails
Content-Type: application/json

{
  "Name": "User",
  "Email": "[email protected]",
  "Password": "12345",
  "CreatedAt": "2005-07-21"
}

2

Answers


  1. What type of rendering mode is it?

    You may have to add

    @rendermode="InteractiveServer"
    

    if it is not set to Interactive mode globally.

    Login or Signup to reply.
  2. Be sure add [SupplyParameterFromForm] and change user to property instead of field like below. The [SupplyParameterFromForm] attribute indicates that the value of the associated property should be supplied from the form data :

    [SupplyParameterFromForm]
    private AccountDetails user { get; set; } = new AccountDetails();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search