text stringlengths 0 13.4k |
|---|
Next, the controller calls into the service layer to do the actual database |
operation of saving the new to-do item: |
var successful = await _todoItemService.AddItemAsync(newItem); |
if (!successful) |
{ |
return BadRequest(new { error = "Could not add item." }); |
} |
The AddItemAsync method will return true or false depending on |
whether the item was successfully added to the database. If it fails for |
some reason, the action will return an HTTP 400 Bad Request error |
along with an object that contains an error message. |
Finally, if everything completed without errors, the action redirects the |
browser to the /Todo/Index route, which refreshes the page and |
displays the new, updated list of to-do items to the user. |
Add a service method |
66 |
Add new to-do items |
If you're using a code editor that understands C#, you'll see red squiggely |
lines under AddItemAsync because the method doesn't exist yet. |
As a last step, you need to add a method to the service layer. First, add it |
to the interface definition in ITodoItemService : |
public interface ITodoItemService |
{ |
Task<TodoItem[]> GetIncompleteItemsAsync(); |
Task<bool> AddItemAsync(TodoItem newItem); |
} |
Then, the actual implementation in TodoItemService : |
public async Task<bool> AddItemAsync(TodoItem newItem) |
{ |
newItem.Id = Guid.NewGuid(); |
newItem.IsDone = false; |
newItem.DueAt = DateTimeOffset.Now.AddDays(3); |
_context.Items.Add(newItem); |
var saveResult = await _context.SaveChangesAsync(); |
return saveResult == 1; |
} |
The newItem.Title property has already been set by ASP.NET Core's |
model binder, so this method only needs to assign an ID and set the |
default values for the other properties. Then, the new item is added to |
the database context. It isn't actually saved until you call |
SaveChangesAsync() . If the save operation was successful, |
SaveChangesAsync() will return 1. |
Try it out |
67 |
Add new to-do items |
Run the application and add some items to your to-do list with the form. |
Since the items are being stored in the database, they'll still be there |
even after you stop and start the application again. |
As an extra challenge, try adding a date picker using HTML and |
JavaScript, and let the user choose an (optional) date for the |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.