text stringlengths 0 13.4k |
|---|
on the ITodoItemService interface, which will return true or false |
depending on whether the update succeeded: |
var successful = await _todoItemService.MarkDoneAsync(id); |
if (!successful) |
{ |
return BadRequest("Could not mark item as done."); |
} |
Finally, if everything looks good, the browser is redirected to the |
/Todo/Index action and the page is refreshed. |
With the view and controller updated, all that's left is adding the missing |
service method. |
Add a service method |
First, add MarkDoneAsync to the interface definition: |
Services/ITodoItemService.cs |
Task<bool> MarkDoneAsync(Guid id); |
72 |
Complete items with a checkbox |
Then, add the concrete implementation to the TodoItemService : |
Services/TodoItemService.cs |
public async Task<bool> MarkDoneAsync(Guid id) |
{ |
var item = await _context.Items |
.Where(x => x.Id == id) |
.SingleOrDefaultAsync(); |
if (item == null) return false; |
item.IsDone = true; |
var saveResult = await _context.SaveChangesAsync(); |
return saveResult == 1; // One entity should have been updated |
} |
This method uses Entity Framework Core and Where() to find an item |
by ID in the database. The SingleOrDefaultAsync() method will either |
return the item or null if it couldn't be found. |
Once you're sure that item isn't null, it's a simple matter of setting the |
IsDone property: |
item.IsDone = true; |
Changing the property only affects the local copy of the item until |
SaveChangesAsync() is called to persist the change back to the database. |
SaveChangesAsync() returns a number that indicates how many entities |
were updated during the save operation. In this case, it'll either be 1 (the |
item was updated) or 0 (something went wrong). |
Try it out |
73 |
Complete items with a checkbox |
Run the application and try checking some items off the list. Refresh the |
page and they'll disappear completely, because of the Where() filter in |
the GetIncompleteItemsAsync() method. |
Right now, the application contains a single, shared to-do list. It'd be |
even more useful if it kept track of individual to-do lists for each user. In |
the next chapter, you'll add login and security features to the project. |
74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.