Activity 4 - Adding a new Razor page
Instructions
Create new page
Ensure that you have Visual Studio Code open and in the Activity bar, Explorer is selected.
In the Solution Explorer, next to the Pages directory, select the Add new file… button.
This will bring up a list of file type.
- Select Razor component from the list.
Name it
todo
and hit Enter.This will create the file and open it in the editor.
Next, you will update the page to add a
@page
directive so that the page responds to /todo and add a page title using the<PageTitle>
tag.
Add link to page from navigation
Locate the navigation menu page (NavMenu.razor) under Shared and open it.
Add a navigation item for your todo list above Fetch Data by copying the Fetch Data
<div>
and changing where it says FetchData or Fetch Data to TodoIn the Solution Explorer, right click on your project name, select Debug and select Start new instance to see the changes view your To Do List.
Create the To Do List
- Create a new Class file called TodoItem.cs to hold a class that represents the todo object.
At the top level of your project, click the Add new file… button and select Class from the list. Give it the name TodoItem
.
- Add the following code to give a TodoItem a
Title
that is astring
and has a property calledIsDone
that is aboolean
.
public class TodoItem
{
public string? Title { get; set; }
public bool IsDone { get; set; }
}
- Go back to the
todo.razor
file and:
- In the @code block, add a List object of
TodoItem
called todos. The Todo component uses this field to maintain the state of the todo list. - Add a heading (
<h3>
) called “Todo” - Under the heading, add an unordered list markup (
<ul>
) and a foreach loop to render each todo item as a list item (<li>
). - Add a text input (
<input>
) that contains a placeholder that says “Something todo” and a button (<button>
) that says “Add todo” below the unordered list
- When you click the Add todo button, nothing happens at this point. Now you’ll need to add an event handler.
- Change the button to include an onclick action.
- In the
@code
block:- add a new string to hold the name of the new todo.
- add a new
AddTodo
method that checks to see if the new string has text. You can do this by using theIsNullOrWhiteSpace
method of the string. If it has text, create a newTodoItem
instance with the text as theTitle
and add that instance to theList
object you created earlier. - Clear the value of the text input by setting
newTodo
to an empty string
- Modify the text
<input>
element to bindnewTodo
with the@bind
attribute.
Update the list so that the titles are editable (
<input>
) and add a checkbox to keep track of completed items. Make sure you@bind
the checkbox to theIsDone
property of thetodo
.Update the
<h3>
to show the count of the number of todos that aren’t complete.Save and Run a new instance of your app so test it out.
You did it!
Workshop complete