• Stars
    star
    104
  • Rank 330,604 (Top 7 %)
  • Language
    HTML
  • License
    MIT License
  • Created almost 5 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Examples of how to manage state in Blazor WebAssembly and Blazor Server apps.

BlazorState

Examples of how to manage state in Blazor WebAssembly and Blazor Server apps.

Free Azure Get your free Azure account

This project is intended to illustrate how to better manage state in Blazor applications. It is based on the official documentation: ASP.NET Core Blazor state management.

To get started, fork the repo (optional) then clone it.

โฌ‡ Download the related presentation from here.

๐Ÿ‘€ Read the related blog post: Blazor State Management.

Stating the Problem

The project contains several variations of a Blazor app for tracking health statistics. (For the background behind the sample app, read: From Angular to Blazor: The Health App). This version follows a layered architecture:

  • The BlazorState.ViewModel project can be shared across .NET Core apps including Xamarin and WPF.
  • The BlazorState.Shared Razor class library contains views, styles, and JavaScript code that can be shared between Blazor WebAssembly and Blazor Server projects. If you're not familiar with the difference, read ASP.NET Core Blazor hosting models.
  • The other projects use the shared code.

Set the BlazorState.Wasm project as the startup project or navigate to the folder if you are running from the command line. Launch the app. In the first page, modify the inputs to see how BMI, BMR, and target heart rate change.

Next, instead of using the built-in navigation, change the URL to /results and refresh. Notice you lose the state you entered.

Try the same thing with BlazorState.Server. For this demo, you can "break the circuit" by stopping the web server. The app will show disconnected. Restart the web server, and the app will refresh but it will lose any state.

Solution 1: Preserve State with Local Storage

Launch BlazorState.WasmLocal (the local is for "local storage") and try the same exercise as before. This time, you should see the state is preserved. You can view the local storage for the app and see the serialized view model. In fact, you can close the browser and reopen it to see the state continues to persist.

Run BlazorState.ServerLocal. This demonstrates the same code for tracking local storage works for the server hosting model as well. It will pre-render with defaults, then re-render with the state.

A few notes:

  • The text is stored "in the clear." For sensitive information, encryption should be added, for example by adding ASP.NET Core Data Protection.
  • The relevant code is contained in the StorageHelper.razor view. This view wraps the routing (App.razor) in both client and server projects. This enables it to plug into the overall app lifecycle.
  • After it is initialized, it attempts to deserialize the state from local storage via JavaScript interop (the simple operations are in wwwroot\stateManagement.js). The operation is wrapped in a try...catch block because storage isn't available when pre-rendering in Blazor Server. The code will be fired a second time once the rendering is complete.
  • Property change notification is used to save state when the model changes.
  • This example uses localStorage which means state will be preserved across tabs. To keep it scoped to a single tab, so each tabbed instance has its own copy of state, use sessionStorage instead.

Solution 2: Preserve State with Server Storage

For this example, launch the server side of the BlazorState.WasmRemote project. This stands up an API to simulate storing state in a database server and also hosts a Blazor WebAssembly project. The same approach will work for Blazor Server.

The API contains an in-memory dictionary that stores state by IP address. This is meant as an illustration only. In production a more likely scenario would be to have the user authenticate then store state in a database with the user as the key.

For this example, a service called StateService is registered. This relies on an instance of IStateServiceConfig to determine what the API endpoint is. The solution has this hard-coded as a local class in Startup.cs. In production this would be a dynamic class that pulls from standard configuration. If the example isn't working, ensure the configuration class has the proper port number.

The service takes a dependency on the view model and is able to immediately register for property change notification. Because it is making HTTP calls to an API, it will work on the server or the client and doesn't require local storage availability. It posts an updated state to the server any time a property changes and exposes an InitAsync method to retrieve the state. It acts like middleware and starts working after it is registered, but the main pages Index.razor and Results.razor make a call when initialized to set up initial state.

I prefer to run this from the command line (dotnet run from the BlazorState.WasmRemote\Server folder) so I can show the serialization calls come in as I update the form.

Conclusion

The goal of this project is to illustrate good practices for preserving state in Blazor apps. It demonstrates an approach to using shared code to maximize reuse across project types. It also takes an approach of using property change notification and service registration to minimize code changes necessary to implement the state management. As always, your feedback is welcome and appreciated.

Jeremy Likness

More Repositories

1

vanillajs-deck

A Vanilla.js Single Page App (SPA) slide deck for a presentation about Vanilla.js written with no frameworks.
JavaScript
190
star
2

BlazorWasmEFCoreExample

Example of a Blazor WebAssembly project that uses Entity Framework Core on the server for data access.
C#
152
star
3

serverless-url-shortener

Azure Function for a URL shortening website. Uses serverless functions, Azure Table Storage and Application Insights.
C#
120
star
4

SqliteWasmHelper

Persistent SQLite in Blazor WebAssembly apps with EF Core 6.0 and your browser's cache.
C#
95
star
5

ExpressionGenerator

Example of creating dynamic LINQ expressions
C#
94
star
6

blazor-wasm

Blazor and WebAssembly examples (part of a Blazor presentation)
JavaScript
80
star
7

ExpressionPowerTools

Power tools for working with IQueryable and Expression trees.
C#
77
star
8

BlazorEFCoreMultitenant

Examples of multitenancy using EF Core and Blazor.
C#
73
star
9

explore-cosmos-db

.NET Core 2.0 project to demonstrate some capabilities of Cosmos DB
C#
71
star
10

DurableDungeon

A game designed to teach and learn serverless durable functions in C#
C#
70
star
11

PlanetaryDocs

A complete Blazor Server app using Azure Cosmos DB with EF Core.
C#
61
star
12

azure-fn-file-process-hol

Tutorial for file processing and importing to SQL leveraging serverless Azure Functions.
C#
46
star
13

jsInject

Simple & easy DI for JavaScript.
JavaScript
45
star
14

PASS-2017

Code samples for the Web API Design workshop at PASS Summit 2017
C#
43
star
15

BlazorHealthApp

Example application ported from Angular 2 to Blazor
HTML
37
star
16

sterling-net-core

This is a port of the Sterling Open Source NoSQL database to .NET Standard 2.0.
C#
35
star
17

BlazorMVVM

Implementation of MVVM pattern in Blazor
HTML
31
star
18

jlik.me

URL Shortener project.
C#
31
star
19

ShortLink

Simple version of link shortener
C#
25
star
20

BlazorOData

Build data-driven apps using LINQ and shared models with Blazor and OData.
C#
23
star
21

Angular2HealthApp

Angular Health App Ported to AngularJS 2.0 (beta)
TypeScript
22
star
22

PlasmaWasmRust

Implementation of plasma effect using WebAssembly compiled from Rust.
Rust
21
star
23

MvpSummitTaskList

Example in MVP summit of using connected services and adding (persisted) SQLite to Blazor Wasm.
HTML
21
star
24

6502emulator

Emulator for the 6502 chipset written with TypeScript and Angular 2
TypeScript
20
star
25

AzureBlazorCosmosWasm

A completely serverless solution to access Cosmos DB from Blazor WebAssembly using EF Core.
C#
19
star
26

BlazorServerEFCoreExample

Example of a Blazor Server App that reuses most of the libraries from the related Blazor WebAssembly App example.
HTML
18
star
27

jeremylikness-blog

Developer for Life Blog
HTML
17
star
28

dotnetconf2021

Demos performed by Jeremy Likness for .NET Conf 2021.
C#
16
star
29

SterlingNoSQL

Sterling NoSQL Object-Oriented Database
C#
16
star
30

usda-microservice

Simple Angular 2, Node.js microservices, and Mongo DB example using Docker compose to get up and running.
TypeScript
16
star
31

ExpressionExplorer

A simple console application to explore and transform expressions using ExpressionVisitor.
C#
16
star
32

QueryEvaluationInterceptor

An example of intercepting IQueryable executions to parse and transform the query.
C#
15
star
33

typescript-for-node

Presentation materials for Connect.Tech 2017. Covers building Node.js apps with TypeScript.
CSS
12
star
34

AdvancedBlazor

An advanced Blazor example demonstrating a Razor class library with embedded JavaScript shared between a Blazor Server and a Blazor WebAssembly project.
HTML
12
star
35

AngularTipsAndTricks

Demonstration app of various Angular Tips and Tricks for DevLink 2014 Talk
JavaScript
12
star
36

jlikness.watch

Simple module to enable counting watches in your AngularJS app.
JavaScript
12
star
37

TypeScript-from-JavaScript

Learn TypeScript through a series of refactorings to existing JavaScript code.
JavaScript
12
star
38

AsyncAwaitExplained

Async/await keywords explained: deck and source demos
C#
12
star
39

redux-adventure

A text adventure written with Redux, Angular 2 and TypeScript.
TypeScript
11
star
40

AngularES6HealthApp

The Angular Health App implemented with ECMAScript 6 and Babel.js
JavaScript
11
star
41

wasm-trees

An example of memory management/passing buffers between WebAssembly and JavaScript
C
10
star
42

Ng2TypeScriptLab

A hands-on lab for building your first AngularJS 2.0 apps with TypeScript.
9
star
43

git-fork-branch-cheatsheet

My cheat sheet for the git/fork/branch workflow
9
star
44

BlazorDebounce

Example of an easy way to debounce input without timers.
HTML
9
star
45

tic-tac-toe-ng2

Tic-Tac-Toe with Computer Opponent written in Angular 2 and TypeScript
TypeScript
9
star
46

ng2ts-workshop

Angular 2 with TypeScript day workshop
TypeScript
9
star
47

PlasmaWasmGo

Implementation of Plasma effect in WebAssembly using Go
JavaScript
8
star
48

Angular2ReduxKendoUIHealthApp

An Angular 2 app using Redux and the Kendo UI Angular 2 controls.
TypeScript
8
star
49

micro-locator

Simple services locator.
TypeScript
8
star
50

build-event-grid

Event Grid publisher and consumer example
C#
8
star
51

intro-to-typescript

Introduction to TypeScript for JavaScript developers
CSS
7
star
52

EFCosmosQuickstart

Mirrors the Azure Cosmos DB quickstart using EF Core 5 and EF Core 6
C#
7
star
53

VanillaJs

An example of using modern JavaScript for framework-free development.
TypeScript
7
star
54

qorlate

Promise correlation for AngularJS
JavaScript
7
star
55

AngularDebuggingAndPerformance

Examples for Angular Debugging and Performance course
JavaScript
6
star
56

SparkMLDocCategorization

Example of automatic categorization using .NET for Spark and ML.NET
C#
6
star
57

StarRepo

A .NET 6.0 ASP.NET Core hosts Blazor WebAssembly app demonstrating client and server GraphQL with HotChocolate.
C#
6
star
58

Event-Grid-Glue

Example Event Grid Application
C#
6
star
59

ng2ts-workshop-v2

Angular and TypeScript workshop initially developed for DevNexus 2017
TypeScript
6
star
60

LearnTypeScript

TypeScript examples
TypeScript
5
star
61

AWSMigration

Migrate from AWS Lambda to Azure Functions
JavaScript
5
star
62

TypeScript2016Prez

Presentation covering thet latest (1.8.x) version of TypeScript with examples and deck.
JavaScript
5
star
63

angular-net

Angular examples using .NET Core.
TypeScript
5
star
64

FoodDatabaseMaui

Food database example
C#
4
star
65

RebuildWinJS

Interactive Windows Store app providing a presentation of what's new with WinJS
HTML
4
star
66

Durable-Registry

A solution for 25 days of serverless to implement a holiday registry using serverless Azure Functions and Durable Functions.
C#
3
star
67

bring-own-app-connect-17

Project example (.NET Core 2.0) for Azure lift and shift talk in Connect() 2017.
C#
3
star
68

WinRTExamples

C#
3
star
69

SomeDb

.NET Conference example EF Core 5.0 app showing simple logging, DebugView, and ToQueryString
C#
3
star
70

TelerikNEXT2015

Deck and Code for TelerikNEXT 2015
CSS
3
star
71

JeremyBookWinJs

A simple example of using WinJS
JavaScript
3
star
72

IQueryableExpressionExamples

Examples for the TDevConf presentation "Inside IQueryable: The Power of .NET Expressions."
C#
3
star
73

Jounce

Jounce, a legacy Silverlight framework based on the MVVM pattern and MEF for dependency injection.
C#
3
star
74

redux6502

6502 Emulator Written in Angular 2 and TypeScript with Redux.
TypeScript
2
star
75

T6502

JavaScript
2
star
76

EFCoreModernDataAccess

EF Core demo application for DEVintersection
C#
2
star
77

jsEventAgg

Lightweight event aggregator (publisher/subscriber) for JavaScript
JavaScript
2
star
78

deepskies

Deep skies navigator BUILD demo.
C#
2
star
79

DurableSearch

Example of using Durable Functions HTTP Task to implement a fan-out/fan-in pattern.
C#
2
star
80

ca-acs

Cloud Academy Azure Container Services Demo Code
JavaScript
2
star
81

awesm-stack

AWESM Stack Deck and Code from Atlanta Code Camp
JavaScript
1
star
82

DotNetDocsBuddy

Your friendly .NET docs assistant.
C#
1
star
83

LearnZoneJs

Learn how to use Zone JS
JavaScript
1
star
84

tsviewmodel

ViewModel implementation in TypeScript using decorators for property change notifications
TypeScript
1
star
85

AngularRoutes

Demonstrates how to use various options for routing in Angular
JavaScript
1
star
86

ZoneJS

Presentation about JavaScript Zones
JavaScript
1
star
87

cdams

CDA Team link shortener
C#
1
star
88

PortableIoC

Portable IOC is a tiny thread-safe Inversion of Control container for Universal Windows Platform apps.
C#
1
star
89

BuildWin8Apps

C#
1
star
90

managing-cloud-data

Demo companion for presentation about managing cloud data
1
star
91

docker-we-rise

Hands-on Docker presentation for the We Rise Women in Technology conference in Atlanta 2017.
HTML
1
star
92

ng2-ts-music-city-code

Angular and TypeScript Development for Music City Code
TypeScript
1
star
93

Ng2TypeScriptPrez

Presentation I gave at the Atlanta .NET User Group about building Angular 2 apps with TypeScript.
JavaScript
1
star
94

Angular2HelloWorld

Simple "Hello, World" app with Angular 2 beta
HTML
1
star