A Very Simple Application
In this lesson, we will use a simple application to put the basics of using controllers into practice.
We'll cover the following
In this lesson, we will modify the customer-list example we saw in previous lessons to turn it into a complete toy-application. More specifically, we will give the user the ability to edit and add new customers.
The application is a toy because it is very simple and we will not store customers in an actual database, but we use a simple class that simulates a customers database table. Our database class implements the singleton pattern and contains the instance of the table-simulation class in an Instance
property. Moreover, we add a principal key Id
property to give a unique identity to each customer. The Id
property will contain a string created by converting a Guid
to a string. This way, we ensure that the Id
is unique without using difficult-to-manage auto-increment counters.
The Guid
strings are not just a trick for the easy implementation of a database simulation but are used in popular distributed databases such as MongoDB and Cosmos DB to avoid the burden of centralized counting.
We also added a Salary
decimal
field in order to show how non-integer numerical fields are dealt with.
The application structure
The HomeController
contains an Index
method that returns all customers and the [HttpGet]
and [HttpHost]
versions of both an Edit
method and an Add
method. The Edit
method modifies existing users while Add
adds new customers.
The user enters the Edit
page by clicking a link in a new column we added to the HTML table that lists all users:
The a
tag refers to our newly added Edit
method. We used nameof
to avoid writing the name of the method as a constant string, which would be an error-prone practice. Moreover, method names written as constant strings cannot be retrieved by engineering tools during code maintenance (tools like “find all occurrences of”). The Edit
action method invoked by the a
tag is passed the customer Id
through the a
tag asp-route-id
attribute, as explained in the tag helpers chapter.
At the bottom of the Index
view, there is a link that invokes the [HttpGet]
version of the Add
action method:
Get hands-on with 1200+ tech skills courses.