Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
<pre>public class AppDbContext : DbContext
    {
        public AppDbContext()
        {

        }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
            }
        }

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    base.OnModelCreating(modelBuilder);
        //    modelBuilder.Entity<User>()
        //}

        public DbSet<User> User { get; set; }
        public DbSet<Item> Items { get; set; }

    }


[Table("Users")]
public class User
{
[Display(AutoGenerateField = false)]
public int UserId { get; set; }

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

[Display(Name = "Password")]
[Required]
[MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
[DataType(DataType.Password)]
public string Password { get; set; }

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

[Display(Name = "Company")]
[StringLength(255)]
[Required(ErrorMessage = "Company is required.")]
[Remote("doesCompanyExist", "Company", HttpMethod = "POST", ErrorMessage = "Company already exists. Please enter a different company.")]
public string Company { get; set; }

public User GetRegisteredUser()
{
return new User
{
UserName = UserName,
Password = Password,
Email = Email,
Company = Company,

};
}

}

@page "/register"

@using TestBlazor.Models

<br />
<br />

<h3>Register</h3>
<br />

<EditForm class="needs-validation" Model="@_user" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
    <div class="alert @StatusClass">@StatusMessage</div>
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-group">
        <p>User name</p>
        <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
        <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Password</p>
        <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
        <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Email</p>
        <input id="email" class="solid" placeholder="you@example.com" @bind-value="_user.Email" />
        <ValidationMessage For="@(() => @_user.Email)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Company</p>
        <input id="company" class="solid" placeholder="Your company.." @bind-value="_user.Company" />
        <ValidationMessage For="@(() => @_user.Company)"></ValidationMessage>
    </div>


    <br />

    <button disabled="@loading" class="btn btn-primary">

        @if (loading)
        {
            
            <NavLink href="/login" class="btn btn-link">Register</NavLink>
        }
        Register
    </button>
    <NavLink href="/login" class="btn btn-link">Login</NavLink>
</EditForm>



@code {
    private User _user = new User();

    private string StatusMessage;
    private string StatusClass;

    private bool loading;


    private void OnValidSubmit()
    {
        if (loading == true)
        {
            Console.WriteLine("You have successfully registered!");
        }

        else
        {
            loading = false;
            Console.WriteLine("Check your information again!");
        }
    }

    protected void HandleValidSubmit()
    {
        StatusClass = "alert-info";
        StatusMessage = " You have successfully registered! Please click the Login button to log in!";
    }

    protected void HandleInvalidSubmit()
    {
        StatusClass = "alert-danger";
        StatusMessage = " Check your information again!";
    }


    public bool doesCompanyExist(string Company)
    {
        try
        {

            if (Company != null)
            {
                return true;
            }

        }
        catch (Exception)
        {
            return false;
        }

        return false;

    }

}



What I have tried:

I'm doing this in Blazor (C #). I tried to write various functions, but I was not able to remember the data when registering in the basic data, so that the user can log in with that data.
Posted
Updated 29-Jun-21 23:30pm
Comments
Chris Copeland 30-Jun-21 4:48am    
Well you've created your database context "AppDbContext", and you've built your entities and created the form. It seems like the only thing you've not done is put all of these things together, have you tried actually using the database context to save data to the database?
Member 15270194 30-Jun-21 4:55am    
Thank you for your reply. How then should I merge this, i.e. that my data is saved when the user registers? I created a database using add-migration nameofmigration and update-database so now I have that Users table empty.
Chris Copeland 30-Jun-21 5:28am    
You need to use the database context you created ("AppDbContext") to interact with the database. Consider looking over this documentation[^] for a starting point. I know it says EFCore but I believe this also applies to the non-core version of EF.

1 solution

It looks like you have the tools you need to be able to insert a user. You just need to make use of the context you have created and configured.

C#
using (var context = new AppDbContext())
{
  context.Users.Add(user);
  context.SaveChanges();
}

This documentation page[^] contains examples of interacting with the database.
 
Share this answer
 
Comments
Member 15270194 30-Jun-21 6:50am    
Thank you for your reply. I tried to add the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestBlazor.Models;

namespace TestBlazor.Data
{
public class Users
{
public static void AddUsers()
{
using (var context = new AppDbContext())
{
//var user = new User { Url = "" }; //what this?
context.User.Add(User); //this is error
context.SaveChanges();
}
}
}
}

but I get an error (I added a new class):
Severity Code Description Project File Line Suppression State
Error CS0119 'User' is a type, which is not valid in the given context TestBlazor C: \ ....
Chris Copeland 30-Jun-21 10:36am    
You're not using the Add() method correctly. You need to instantiate an instance of User and pass that into the method. The line you have commented out is the part where you'd create the user class, set the properties and then add it to the context.

You need to do more research into Entity Framework and how to use it. From your existing code you would need to put the logic in the HandleValidSubmit method, and populate it with elements from the form.
Member 15270194 1-Jul-21 4:18am    
Thanks a lot for the reply. Here's what I've done so far:
public class Users
{

private readonly AppDbContext _dataContext;
private User _user = new User();

public Users(AppDbContext dataContext)
{
_dataContext = dataContext;
}
public void AddUsers(User user)
{
var users = new User
{
UserName = user.UserName,
Password=user.Password,
Email=user.Email,
Company=user.Company
};
_dataContext.User.Add(users);
_dataContext.SaveChanges();
}
}
I'm interested in the HandleValidSubmit function, should that function remain in Register.razor? Or should we call what I wrote AddUsers in that function?
Chris Copeland 1-Jul-21 4:27am    
That's up to you to decide, I can't write your application for you. You have the classes and tools you need to handle the user addition. You have your form elements, each containing the fields needed for the user, and you have the backing C# code which will execute something when the form has been filled in. Just take the form elements, populate your user object, and then call database context.
Member 15270194 1-Jul-21 6:58am    
Thanks for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900