Erstellen einer Blazor-App mit einer AufgabenlisteBuild a Blazor todo list app
Von Daniel Roth und Luke LathamBy Daniel Roth and Luke Latham
In diesem Tutorial erfahren Sie, wie Sie eine Blazor-App erstellen und ändern.This tutorial shows you how to build and modify a Blazor app. Sie lernen Folgendes:You learn how to:
- Erstellen eines Aufgabenlisten-Blazor-App-ProjektsCreate a todo list Blazor app project
- Ändern von Razor-KomponentenModify Razor components
- Verwenden von Ereignisbehandlung und Datenbindung in KomponentenUse event handling and data binding in components
- Verwenden von Routing in einer Blazor-AppUse routing in a Blazor app
Am Ende dieses Tutorials verfügen Sie über eine funktionierende Aufgabenlisten-App.At the end of this tutorial, you'll have a working todo list app.
VoraussetzungenPrerequisites
Erstellen einer Aufgabenlisten-Blazor-AppCreate a todo list Blazor app
Erstellen Sie in einer Befehlsshell eine neue Blazor-App namens
TodoList
:Create a new Blazor app namedTodoList
in a command shell:dotnet new blazorserver -o TodoList
Mit dem obigen Befehl wird ein Ordner mit dem Namen
TodoList
mit der-o|--output
-Option zum Speichern der App erstellt.The preceding command creates a folder namedTodoList
with the-o|--output
option to hold the app. DerTodoList
-Ordner ist der Stammordner des Projekts.TheTodoList
folder is the root folder of the project. Ändern Sie das Verzeichnis mit dem folgenden Befehl in den OrdnerTodoList
:Change directories to theTodoList
folder with the following command:cd TodoList
Fügen Sie der App mithilfe des folgenden Befehls eine neue
Todo
Razor-Komponente hinzu:Add a newTodo
Razor component to the app using the following command:dotnet new razorcomponent -n Todo -o Pages
Die Option
-n|--name
im vorherigen Befehl gibt den Namen der neuen Razor-Komponente an.The-n|--name
option in the preceding command specifies the name of the new Razor component. Die neue Komponente wird im OrdnerPages
des Projekts mit der-o|--output
-Option erstellt.The new component is created in the project'sPages
folder with the-o|--output
option.Wichtig
Der erste Buchstabe von Razor-Komponentendateinamen muss großgeschrieben werden.Razor component file names require a capitalized first letter. Öffnen Sie den
Pages
-Ordner. Überprüfen Sie, ob derTodo
-Komponentendateiname mit einem großgeschriebenen ersten Buchstaben (T
) beginnt.Open thePages
folder and confirm that theTodo
component file name starts with a capital letterT
. Der Dateiname sollteTodo.razor
lauten.The file name should beTodo.razor
.Öffnen Sie die
Todo
-Komponente in einem beliebigen Datei-Editor, und fügen Sie am Anfang der Datei eine@page
Razor-Anweisung mit der relativen URL/todo
hinzu.Open theTodo
component in any file editor and add an@page
Razor directive to the top of the file with a relative URL of/todo
.Pages/Todo.razor
:Pages/Todo.razor
:@page "/todo" <h3>Todo</h3> @code { }
Speichern Sie die Datei
Pages/Todo.razor
.Save thePages/Todo.razor
file.Fügen Sie der Navigationsleiste die
Todo
-Komponente hinzu.Add theTodo
component to the navigation bar.Die Komponente
NavMenu
wird im Layout der App verwendet.TheNavMenu
component is used in the app's layout. Layouts sind Komponenten, mit denen Sie die Duplizierung des Inhalts in einer App vermeiden können.Layouts are components that allow you to avoid duplication of content in an app. DieNavLink
-Komponente zeigt einen Hinweis auf der Benutzeroberfläche der App an, wenn die Komponenten-URL von der App geladen wird.TheNavLink
component provides a cue in the app's UI when the component URL is loaded by the app.Fügen Sie in der ungeordneten Liste (
<ul>...</ul>
) derNavMenu
-Komponente das folgende Listenelement (<li>...</li>
) und die folgendeNavLink
-Komponente für dieTodo
-Komponente hinzu.In the unordered list (<ul>...</ul>
) of theNavMenu
component, add the following list item (<li>...</li>
) andNavLink
component for theTodo
component.In
Shared/NavMenu.razor
:InShared/NavMenu.razor
:<ul class="nav flex-column"> ... <li class="nav-item px-3"> <NavLink class="nav-link" href="todo"> <span class="oi oi-list-rich" aria-hidden="true"></span> Todo </NavLink> </li> </ul>
Speichern Sie die Datei
Shared/NavMenu.razor
.Save theShared/NavMenu.razor
file.Erstellen Sie die App, und führen Sie sie aus, indem Sie den
dotnet watch run
-Befehl in der Befehlsshell im OrdnerTodoList
ausführen.Build and run the app by executing thedotnet watch run
command in the command shell from theTodoList
folder. Wenn die App ausgeführt wird, navigieren Sie zur neuen To-do-Seite, indem Sie in der Navigationsleiste der App den LinkTodo
auswählen, der die Seite unter/todo
lädt.After the app is running, visit the new Todo page by selecting theTodo
link in the app's navigation bar, which loads the page at/todo
.Lassen Sie die App die Befehlsshell weiter ausführen.Leave the app running the command shell. Jedes Mal, wenn eine Datei gespeichert wird, wird die App automatisch erneut erstellt.Each time a file is saved, the app is automatically rebuilt. Die Verbindung zwischen dem Browser und der App wird während der Kompilierung und des Neustarts vorübergehend unterbrochen.The browser temporarily loses its connection to the app while compiling and restarting. Die Seite im Browser wird automatisch erneut geladen, wenn die Verbindung wiederhergestellt wird.The page in the browser is automatically reloaded when the connection is re-established.
Fügen Sie dem Stamm des Projekts (der
TodoList
-Ordner) eineTodoItem.cs
-Datei hinzu, die eine Klasse zum Darstellen eines Aufgabenelements enthalten soll.Add aTodoItem.cs
file to the root of the project (theTodoList
folder) to hold a class that represents a todo item. Verwenden Sie den folgenden C#-Code für dieTodoItem
-Klasse.Use the following C# code for theTodoItem
class.TodoItem.cs
:TodoItem.cs
:public class TodoItem { public string Title { get; set; } public bool IsDone { get; set; } }
Navigieren Sie zur
Todo
-Komponente zurück, und führen Sie Folgendes durch:Return to theTodo
component and perform the following tasks:- Fügen Sie ein Feld für die To-Do-Elemente im
@code
-Block hinzu.Add a field for the todo items in the@code
block. DieTodo
-Komponente verwaltet mit diesem Feld den Status der Aufgabenliste.TheTodo
component uses this field to maintain the state of the todo list. - Fügen Sie ein Markup für eine unsortierte Liste und eine
foreach
-Schleife hinzu, um jedes Aufgabenelement als Listenelement zu rendern (<li>
).Add unordered list markup and aforeach
loop to render each todo item as a list item (<li>
).
Pages/Todo.razor
:Pages/Todo.razor
:@page "/todo" <h3>Todo</h3> <ul> @foreach (var todo in todos) { <li>@todo.Title</li> } </ul> @code { private IList<TodoItem> todos = new List<TodoItem>(); }
- Fügen Sie ein Feld für die To-Do-Elemente im
Die App benötigt Benutzeroberflächenelemente, damit der Liste Aufgabenelemente hinzugefügt werden können.The app requires UI elements for adding todo items to the list. Fügen Sie eine Texteingabe (
<input>
) und eine Schaltfläche (<button>
) unterhalb der Liste (<ul>...</ul>
) hinzu:Add a text input (<input>
) and a button (<button>
) below the unordered list (<ul>...</ul>
):@page "/todo" <h3>Todo</h3> <ul> @foreach (var todo in todos) { <li>@todo.Title</li> } </ul> <input placeholder="Something todo" /> <button>Add todo</button> @code { private IList<TodoItem> todos = new List<TodoItem>(); }
Speichern Sie die Datei
TodoItem.cs
und die aktualisierte DateiPages/Todo.razor
.Save theTodoItem.cs
file and the updatedPages/Todo.razor
file. In der Befehlsshell wird die App automatisch neu erstellt, wenn die Dateien gespeichert werden.In the command shell, the app is automatically rebuilt when the files are saved. Der Browser verliert vorübergehend seine Verbindung mit der App und lädt die Seite dann neu, wenn die Verbindung erneut hergestellt wird.The browser temporarily loses its connection to the app and then reloads the page when the connection is re-established.Bei Auswahl der Schaltfläche
Add todo
geschieht nichts, da kein Ereignishandler mit der Schaltfläche verknüpft ist.When theAdd todo
button is selected, nothing happens because an event handler isn't attached to the button.Fügen Sie der
Todo
-Komponente eineAddTodo
-Methode hinzu, und registrieren Sie die Methode für die Schaltfläche mithilfe des@onclick
-Attributs.Add anAddTodo
method to theTodo
component and register the method for the button using the@onclick
attribute. Die C#-MethodeAddTodo
wird aufgerufen, wenn die Schaltfläche ausgewählt wird:TheAddTodo
C# method is called when the button is selected:<input placeholder="Something todo" /> <button @onclick="AddTodo">Add todo</button> @code { private IList<TodoItem> todos = new List<TodoItem>(); private void AddTodo() { // Todo: Add the todo } }
Fügen Sie am oberen Rand des
@code
-Blocks einnewTodo
-Zeichenfolgenfeld hinzu, um den Titel des neuen To-do-Elements zu erhalten:To get the title of the new todo item, add anewTodo
string field at the top of the@code
block:@code { private IList<TodoItem> todos = new List<TodoItem>(); private string newTodo; ... }
Ändern Sie das
<input>
-Textelement, umnewTodo
mit dem@bind
-Attribut zu verknüpfen:Modify the text<input>
element to bindnewTodo
with the@bind
attribute:<input placeholder="Something todo" @bind="newTodo" />
Aktualisieren Sie die
AddTodo
-Methode, um dasTodoItem
mit dem angegebenen Titel der Liste hinzuzufügen.Update theAddTodo
method to add theTodoItem
with the specified title to the list. Löschen Sie den Wert der Texteingabe, indem Sie fürnewTodo
eine leere Zeichenfolge festlegen:Clear the value of the text input by settingnewTodo
to an empty string:@page "/todo" <h3>Todo</h3> <ul> @foreach (var todo in todos) { <li>@todo.Title</li> } </ul> <input placeholder="Something todo" @bind="newTodo" /> <button @onclick="AddTodo">Add todo</button> @code { private IList<TodoItem> todos = new List<TodoItem>(); private string newTodo; private void AddTodo() { if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } }
Speichern Sie die Datei
Pages/Todo.razor
.Save thePages/Todo.razor
file. Die App wird automatisch in der Befehlsshell neu erstellt.The app is automatically rebuilt in the command shell. Die Seite wird nach dem erneuten Verbinden des Browsers mit der App im Browser neu geladen.The page reloads in the browser after the browser reconnects to the app.Der Titeltext für die einzelnen Aufgabenelemente kann als bearbeitbar festgelegt werden, und ein Kontrollkästchen kann dem Benutzer helfen, die erledigten Elemente nachzuverfolgen.The title text for each todo item can be made editable, and a check box can help the user keep track of completed items. Fügen Sie für jedes Aufgabenelement eine Kontrollkästcheneingabe hinzu, und binden Sie ihren Wert an die
IsDone
-Eigenschaft.Add a check box input for each todo item and bind its value to theIsDone
property. Ändern Sie@todo.Title
in ein<input>
-Element, das mit@bind
mittodo.Title
verknüpft ist:Change@todo.Title
to an<input>
element bound totodo.Title
with@bind
:<ul> @foreach (var todo in todos) { <li> <input type="checkbox" @bind="todo.IsDone" /> <input @bind="todo.Title" /> </li> } </ul>
Aktualisieren Sie den
<h3>
-Header, um die Anzahl der nicht abgeschlossene To-do-Elemente anzuzeigen (IsDone
istfalse
).Update the<h3>
header to show a count of the number of todo items that aren't complete (IsDone
isfalse
).<h3>Todo (@todos.Count(todo => !todo.IsDone))</h3>
Die fertige
Todo
-Komponente (Pages/Todo.razor
):The completedTodo
component (Pages/Todo.razor
):@page "/todo" <h3>Todo (@todos.Count(todo => !todo.IsDone))</h3> <ul> @foreach (var todo in todos) { <li> <input type="checkbox" @bind="todo.IsDone" /> <input @bind="todo.Title" /> </li> } </ul> <input placeholder="Something todo" @bind="newTodo" /> <button @onclick="AddTodo">Add todo</button> @code { private IList<TodoItem> todos = new List<TodoItem>(); private string newTodo; private void AddTodo() { if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } }
Speichern Sie die Datei
Pages/Todo.razor
.Save thePages/Todo.razor
file. Die App wird automatisch in der Befehlsshell neu erstellt.The app is automatically rebuilt in the command shell. Die Seite wird nach dem erneuten Verbinden des Browsers mit der App im Browser neu geladen.The page reloads in the browser after the browser reconnects to the app.Fügen Sie Elemente hinzu, und markieren Sie To-do-Elemente als abgeschlossen, um die Komponente zu testen.Add items, edit items, and mark todo items done to test the component.
Wenn Sie fertig sind, fahren Sie die App in der Befehlsshell herunter.When finished, shut down the app in the command shell. In vielen Befehlsshells kann der Tastaturbefehl STRG+C verwendet werden, um eine App anzuhalten.Many command shells accept the keyboard command Ctrl+c to stop an app.
Nächste SchritteNext steps
In diesem Tutorial haben Sie gelernt, wie die folgenden Aufgaben ausgeführt werden:In this tutorial, you learned how to:
- Erstellen eines Aufgabenlisten-Blazor-App-ProjektsCreate a todo list Blazor app project
- Ändern von Razor-KomponentenModify Razor components
- Verwenden von Ereignisbehandlung und Datenbindung in KomponentenUse event handling and data binding in components
- Verwenden von Routing in einer Blazor-AppUse routing in a Blazor app
Informationen über Tools für ASP.NET-Core Blazor:Learn about tooling for ASP.NET Core Blazor: