InteractiveServer
For an interactive web application, it is important to have some way to maintain state. In ASP.NET Blazor, we can keep C# fields in memory while a user interacts on a page.
To use InteractiveServer
, we must specify it with the rendermode directive. This changes how Blazor processes the page. We specify a code block on an InteractiveServer
page.
To begin, this example is similar to the Counter
example included with Blazor, but with a few small changes. We include the System.Text
namespace with a using directive.
string
array, a List
of ints, and a random number generator.AddNumber()
and Output()
functions, and these are called by the Razor markup within the Button
and paragraph elements.AddNumber
is run, and this modifies the numbers List
.Output()
is called, and this is always kept current on each button click—the result of Output is always present in the paragraph.@page "/interactive" @rendermode InteractiveServer @using System.Text <button @onclick="AddNumber">Add random animal</button> <p>@Output()</p> @code { string[] animals = {"bird", "frog", "cat"}; List<int> numbers = new List<int>(); Random rand = new Random(); void AddNumber() { // Add a random number to the list. numbers.Add(rand.Next()); } string Output() { // Generates a string for the output paragraph based on the contents of the fields in memory. var builder = new StringBuilder(); foreach (var number in numbers) { builder.Append(animals[number % animals.Length]); builder.Append(' '); } return builder.ToString(); } }
Because we are in InteractiveServer
mode, the values specified within the Razor markup (like Output) are always kept current. We do not need to do any invalidation ourselves.
List
is changed, the Output function is automatically run to ensure the page is kept up-to-date.With InteractiveServer
in Blazor, we have a powerful way to build web apps that are kept up-to-date based on C# code. Pages are invalidated automatically, which means we can focus on other things.