1
votes

I try to expand the server side blazor todo app.

I would like to

  • add a responsible person to a todoitem
  • add a todoitem after onkeyup inside the input field

This gist contains my attempt to expand the todo app

What works

Adding a list of people inside a select field

<select>
    @foreach (var person in people)
    { 
       <option value="person">@person</option>
    }
</select>

What does not work

Two things are not working

  1. adding a person to a todoItem inside AddTodo()
  2. adding a todoItem for the event onKeyUp == Enter

The method

private void AddTodo()
{
    if (!string.IsNullOrWhiteSpace(newTodo))
    {
        todos.Add(new TodoItem { Title = newTodo, Responsible = person});
        newTodo = string.Empty;
    }
}

Questions

  1. How can multiple form values (input, select) be bound to a method?
  2. Why is onkeyup not firing?

Source code of my Todo.razor gist

Blazor server side todo app

1

1 Answers

2
votes

The cause for why is onkeyup not firing? was a silly mistake; the event handler was attached to the wrong input. This seems to work

<input placeholder="Something todo" @bind="newTodo" @onkeyup="AddTodoOnEnter" />

To get a value from a selected option from a select-tag to your code you bind the variable @newPerson on the select-tag.

<select @bind="newPerson">
@foreach (var person in people)
{
    <option value="@person" >@person.name (@person.id)</option>
}
</select>

You can access it inside the @code section with

@code {
// named tuple list  
private  List<(int id, string name)> people = new List<(int id, string name)>() 
    { 
       (1, "Tom"), (2, "Luise"), (3,"Jane") 
    };

private void AddTodo()
{
  if (!string.IsNullOrWhiteSpace(newTodo))
  {
     todos.Add(new TodoItem { Title = newTodo, Responsible = "who " + newPerson });
     newTodo = string.Empty;
  }
}

Screenshot of the html

Blazor Todo app with select

Current Code / Gist

I updated my gist - you can see the old code next the revision 4 side by side here