Blazor

Blazor

Blazor is a free and open-source web framework that enables developers to create web apps using C# and HTML. Blazor is a framework for building interactive client-side web UI with .NET.
  • Create rich interactive UIs using C# instead of JavaScript.
  • Share server-side and client-side app logic written in .NET.
  • Render the UI as HTML and CSS for wide browser support, including mobile browsers.
  • Integrate with modern hosting platforms, such as Docker.

Create Blazor App

To start, we will create an ASP.NET Core hosted Blazor App project. The project type comes with all template files to create a Blazor application before adding anything. Let's open Visual Studio 2019. If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
On the start window, choose Create a new project.
On the Create a new project window, enter or type blazor in the search box. Next, choose C# from the Language list. Select the Blazor App template, and then choose Next.
In the Configure your new project window, type or enter EFCore5InBlazorApp in the Project name box and click on the Create button.
Now select the Blazor WebAssembly App project template and select the ASP.NET Core hosted check box. Click on the Create button to create an ASP.NET Core-hosted application.
Visual Studio opens your new project and includes the default code files in your project as shown in the Solution Explorer. You will see that 3 projects are created inside this solution.
  • EFCore5InBlazorApp.Client: It has the client-side code and contains the pages that will be rendered on the browser.
  • EFCore5InBlazorApp.Server: It has the server-side code, such as DB related operations and the web API.
  • EFCore5InBlazorApp.Shared: It contains the shared code that can be accessed by both client and server.

Install Entity Framework Core

To use Entity Framework Core we need to install Microsoft.EntityFrameworkCore library in the EFCore5InBlazorApp.Server project. It is available as a nuget package, and you can install it using Nuget Package Manager.
In the Package Manager Console window, enter the following command.
1
PM> Install-Package Microsoft.EntityFrameworkCore
Copied!
For SQL Server LocalDB, which is installed with Visual Studio, we need to install Microsoft.EntityFrameworkCore.SqlServer and will get all the packages required for EF Core.
1
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
Copied!
We also need to install the following NuGet package.
1
PM> Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
Copied!

Create a Data Model and Database Context

To add a data model to the application, right-click on EFCore5InBlazorApp.Shared project and then select Add > New Folder and name the folder Models. Right-click on the Models folder and select Add > Class..., enter a class file name Author.cs, and add the following code.
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
​
7
namespace EFCore5InBlazorApp.Shared.Models
8
{
9
public class Author
10
{
11
public string Id { get; set; }
12
public string Name { get; set; }
13
public string Gender { get; set; }
14
public string Address { get; set; }
15
}
16
}
Copied!
So let's create a folder in your project by right-clicking on EFCore5InBlazorApp.Server project in Solution Explorer and click Add > New Folder. Name the folder DAL (Data Access Layer). In that folder, create a new class file named AuthorContext.cs, and replace the following code.
1
using EFCore5InBlazorApp.Shared.Models;
2
using Microsoft.EntityFrameworkCore;
3
using System;
4
using System.Collections.Generic;
5
using System.Linq;
6
using System.Threading.Tasks;
7
​
8
namespace EFCore5InBlazorApp.Server.DAL
9
{
10
public class AuthorContext : DbContext
11
{
12
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
13
{
14
optionsBuilder.UseSqlServer(@"Data Source=(localdb)\\ProjectsV13;Initial Catalog=AuthorDb;Trusted_Connection=True;MultipleActiveResultSets=true");
15
}
16
​
17
public DbSet<Author> Authors { get; set; }
18
}
19
}
Copied!

Register Context Class

To register AuthoContext as a service, open Startup.cs from EFCore5InBlazorApp.Server project, and call the AddDnContext in the ConfigureServices method.
1
// This method gets called by the runtime. Use this method to add services to the container.
2
public void ConfigureServices(IServiceCollection services)
3
{
4
services.AddDbContext<BookStore>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
5
services.AddControllersWithViews();
6
}
Copied!
The name of the connection string is passed into the context by calling a method on a DbContextOptionsBuilder object.

Setup Connection String

For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file. So let's add the connection to that file as shown below.
1
{
2
"ConnectionStrings": {
3
"DefaultConnection": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=AuthorDb;Trusted_Connection=True;MultipleActiveResultSets=true"
4
},
5
"Logging": {
6
"LogLevel": {
7
"Default": "Information",
8
"Microsoft": "Warning",
9
"Microsoft.Hosting.Lifetime": "Information"
10
}
11
},
12
"AllowedHosts": "*"
13
}
Copied!
The above connection string specifies that the Entity Framework will use a LocalDB database named AuthorDb.

Initialize Database

The Entity Framework will create an empty database for you. So we need to write a method that's called after the database is created to populate it with test data.
In the DAL folder of EFCore5InBlazorApp.Server project, add a new class AuthorContextInitializer and replace the following code.
1
using EFCore5InBlazorApp.Shared.Models;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Threading.Tasks;
6
​
7
namespace EFCore5InBlazorApp.Server.DAL
8
{
9
public class AuthorContextInitializer
10
{
11
public static void Initialize(AuthorContext context)
12
{
13
​
14
context.Database.EnsureCreated();
15
​
16
// Look for any authors.
17
if (context.Authors.Any())
18
{
19
return; // DB has been seeded
20
}
21
​
22
var authors = new List<Author>
23
{
24
new Author { Name="Carson Alexander", Gender="Male", Address = "Skagen 21, Stavanger, Norway"},
25
new Author { Name="Meredith Alonso", Gender="Female", Address = "Keskuskatu 45, Helsinki, Finland"},
26
new Author { Name="Arturo Anand", Gender="Male", Address = "305 - 14th Ave. S. Suite 3B, Seattle, USA"},
27
};
28
​
29
authors.ForEach(a => context.Authors.Add(a));
30
context.SaveChanges();
31
​
32
}
33
}
34
}
Copied!
  • The above code creates a database when needed and loads test data into the new database.
  • It also checks if there are any authors in the database, and if not, it assumes the database is new and needs to be seeded with test data.
In Program.cs file of EFCore5InBlazorApp.Server project, replace the following code in the Main method.
1
using EFCore5InBlazorApp.Server.DAL;
2
using Microsoft.AspNetCore.Hosting;
3
using Microsoft.Extensions.Configuration;
4
using Microsoft.Extensions.DependencyInjection;
5
using Microsoft.Extensions.Hosting;
6
using Microsoft.Extensions.Logging;
7
using System;
8
using System.Collections.Generic;
9
using System.Linq;
10
using System.Threading.Tasks;
11
​
12
namespace EFCore5InBlazorApp.Server
13
{
14
public class Program
15
{
16
public static void Main(string[] args)
17
{
18
var host = CreateHostBuilder(args).Build();
19
​
20
using (var scope = host.Services.CreateScope())
21
{
22
var services = scope.ServiceProvider;
23
try
24
{
25
var context = services.GetRequiredService<AuthorContext>();
26
AuthorContextInitializer.Initialize(context);
27
}
28
catch (Exception ex)
29
{
30
var logger = services.GetRequiredService<ILogger<Program>>();
31
logger.LogError(ex, "An error occurred while seeding the database.");
32
}
33
}
34
​
35
host.Run();
36
}
37
​
38
public static IHostBuilder CreateHostBuilder(string[] args) =>
39
Host.CreateDefaultBuilder(args)
40
.ConfigureWebHostDefaults(webBuilder =>
41
{
42
webBuilder.UseStartup<Startup>();
43
});
44
}
45
}
Copied!

Create Web API Controller

To create a controller, right-click the Controllers folder in EFCore5InBlazorApp.Server, and select Add > Controller... and it will open the Add Scaffold dialog box.
Select API Controller - Empty, and then click the Add button.
Select API Controller - Empty, enter AuthorController (not AuthorsController) as a Controller name and click the Add button. It will create an empty controller, let's add the following code which contains all the basic CRUD operations.
1
using EFCore5InBlazorApp.Server.DAL;
2
using EFCore5InBlazorApp.Shared.Models;
3
using Microsoft.AspNetCore.Http;
4
using Microsoft.AspNetCore.Mvc;
5
using Microsoft.EntityFrameworkCore;
6
using System;
7
using System.Collections.Generic;
8
using System.Linq;
9
using System.Threading.Tasks;
10
​
11
namespace EFCore5InBlazorApp.Server.Controllers
12
{
13
[Route("api/[controller]")]
14
[ApiController]
15
public class AuthorController : ControllerBase
16
{
17
AuthorContext context = new AuthorContext();
18
​
19
[HttpGet]
20
[Route("Index")]
21
public IEnumerable<Author> Index()
22
{
23
return context.Authors.ToList();
24
}
25
​
26
[HttpPost]
27
[Route("Create")]
28
public void Create([FromBody] Author author)
29
{
30
if (ModelState.IsValid)
31
{
32
context.Authors.Add(author);
33
context.SaveChanges();
34
}
35
}
36
​
37
[HttpGet]
38
[Route("Details/{id}")]
39
public Author Details(int id)
40
{
41
Author author = context.Authors.Find(id);
42
return author;
43
}
44
​
45
[HttpPut]
46
[Route("Edit")]
47
public void Edit([FromBody] Author author)
48
{
49
if (ModelState.IsValid)
50
{
51
context.Entry(author).State = EntityState.Modified;
52
context.SaveChanges();
53
}
54
}
55
​
56
[HttpDelete]
57
[Route("Delete/{id}")]
58
public void Delete(int id)
59
{
60
Author author = context.Authors.Find(id);
61
context.Authors.Remove(author);
62
context.SaveChanges();
63
}
64
}
65
}
Copied!

Add Views

To display all the authors, we need to create a view by right-clicking on the Pages folder in EFCore5InBlazorApp.Client project and select Add > Razor Component...
Select Razor Component, enter GetAuthors.razor as a Name, and click the Add button. It will create an empty view and then add the following code.
1
@page "/getauthors"
2
@using EFCore5InBlazorApp.Shared.Models
3
@inject HttpClient Http
4
​
5
<h1>Authors</h1>
6
​
7
<p>This component demonstrates fetching Author data from the server.</p>
8
​
9
<p>
10
<a href="/addauthor">Create New</a>
11
</p>
12
​
13
@if (authors == null)
14
{
15
<p><em>Loading...</em></p>
16
}
17
else
18
{
19
<table class='table'>
20
<thead>
21
<tr>
22
<th>Name</th>
23
<th>Gender</th>
24
<th>Address</th>
25
</tr>
26
</thead>
27
<tbody>
28
@foreach (var author in authors)
29
{
30
<tr>
31
<td>@author.Name</td>
32
<td>@author.Gender</td>
33
<td>@author.Address</td>
34
<td>
35
<a href='/editemployee/@author.Id'>Edit</a> |
36
<a href='/delete/@author.Id'>Delete</a>
37
</td>
38
</tr>
39
}
40
</tbody>
41
</table>
42
}
43
@code {
44
​
45
Author[] authors;
46
​
47
protected override async Task OnInitializedAsync()
48
{
49
authors = await Http.GetFromJsonAsync<Author[]>("/api/Author/Index");
50
}
51
}
Copied!
Now let's add one more page that will use to add a new author, call it AddAuthor.razor, and add the following code.
1
@page "/addauthor"
2
@using EFCore5InBlazorApp.Shared.Models
3
@inject HttpClient Http
4
@inject NavigationManager urlNavigationManager
5
​
6
<h1>Create Author</h1>
7
<hr />
8
​
9
<EditForm Model="@author" OnValidSubmit="CreateAuthor">
10
<DataAnnotationsValidator />
11
<div class="form-group row">
12
<label class="control-label col-md-12">Name</label>
13
<div class="col-md-4">
14
<input class="form-control" @bind="author.Name" />
15
</div>
16
<ValidationMessage For="@(() => author.Name)" />
17
</div>
18
<div class="form-group row">
19
<label class="control-label col-md-12">Gender</label>
20
<div class="col-md-4">
21
<select class="form-control" @bind="author.Gender">
22
<option value="">-- Select Gender --</option>
23
<option value="Male">Male</option>
24
<option value="Female">Female</option>
25
</select>
26
</div>
27
<ValidationMessage For="@(() => author.Gender)" />
28
</div>
29
<div class="form-group row">
30
<label class="control-label col-md-12">Address</label>
31
<div class="col-md-4">
32
<input class="form-control" @bind="author.Address" />
33
</div>
34
<ValidationMessage For="@(() => author.Address)" />
35
</div>
36
<div class="form-group">
37
<button type="submit" class="btn btn-primary">Save</button>
38
<button class="btn btn-light" @onclick="Cancel">Cancel</button>
39
</div>
40
</EditForm>
41
​
42
@code {
43
Author author = new Author();
44
​
45
protected async Task CreateAuthor()
46
{
47
await Http.PostAsJsonAsync("/api/Author/Create", author);
48
urlNavigationManager.NavigateTo("/getauthors");
49
}
50
​
51
void Cancel()
52
{
53
urlNavigationManager.NavigateTo("/getauthors");
54
}
55
}
Copied!
Let's run your application and click on the Authors menu option.
To add a new author click on the Create New link and it will open the Create Author Page.
Enter Name, Gender, and Address and click on the Save button and you will see a new author is added.
Last modified 4mo ago