Home
C#.ASP.NET
InteractiveServer Use (Blazor)
This page was last reviewed on Dec 31, 2023.
Dot Net Perls
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.
Example. 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.
Start We specify a button element with an onclick attribute, and a paragraph that calls an Output function in the Razor markup.
Info In the code block, we have 3 fields: a string array, a List of ints, and a random number generator.
Then We have an AddNumber() and Output() functions, and these are called by the Razor markup within the Button and paragraph elements.
Result When the user clicks the button, AddNumber is run, and this modifies the numbers List.
Finally 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(); } }
Some important points. 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.
And When the 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 31, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.