In this part we would work on generating all our controllers. The code generator would help use do the following:
- generate the controller class
- create the methods
- generated the views
Isn’t this amazing! We’ll be getting so much done with little or no code written. So let’s dive right in!
1. Update You Dependencies
So far, everything have worked fine. Do you remember the version of Entity Framework we installed in Part 3 ? It was 3.1.6. Now we would upgrade to 5.0.7 for all the three dependencies. Follow the steps below:
Step 1 – Open Nugget Package Manager (right-click on the project and select Manage Nugget Packages)
Step 2 – Click on the Installed tab. Then select each of the 3 packages and uninstall them.
Step 3 – Follow the procedure in Part 3 and install them but this time use version 5.0.7.
Step 4 – Finally, you need to install one more package: EnityFrameworkCore.SQLServer like so:
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.7
Now we are ready to start adding the controllers.
2. Create the Controllers
We would create the controllers inside the Controllers folder. Let’s start with Rooms.
Step 1 – Right-click on the Controllers folder and choose Add > Controller
Step 2 – Select MVC Controller with view using Entity Framework and click on Add
Step 3 – In the next window, specify the Data model, context and choose the layout. This is shown below. Then click on Add
After a some seconds, you will notice that the RoomsController class been generated for you. Also the Views have been generated in the Views folder.
3. Test and Fix Errors
Lets’ do some testing!
Launch the application to make sure it works. Then navigate to /rooms
The rooms list view is displayed as shown below:
Now if you click on Create New or Edit, you’ll have an error page. To fix this follow the two steps below:
Step 1 – Open the _Layout.cshtml page in the Views/Shared folder
Step 2 – In the header section, adjust the <link> tag like so
<link href="~/css/styles.css" rel="stylesheet" />
(simply add ~/ before the css)
Step 3 – Scroll down to just before the </body> tag and add this code
@await RenderSectionAsync("Scripts", required: false)
At this point, you can launch the application and make sure it works well. Also try out Create New, Edit and Delete.
Finally, go ahead to create other controllers (you can see the video). But it follows exactly the same procedure.