The provided content outlines a comprehensive tutorial for building a web application that manages a car gallery using ASP.NET Core MVC and MongoDB.
Abstract
The web content serves as an in-depth guide for developers aiming to create a web application with ASP.NET Core MVC that interfaces with MongoDB for data storage and retrieval. It details the necessary tools, such as Visual Studio 2019, .NET Core SDK, and MongoDB, and provides step-by-step instructions for MongoDB installation, database and collection setup, project creation, and the implementation of CRUD operations. The tutorial emphasizes the use of the MongoDB C# driver in the service layer, integrates dependency injection for service management, and demonstrates how to scaffold MVC controller actions along with corresponding views for index, create, edit, details, and delete functionality. The article concludes with a reference to a GitHub repository containing the complete project and encourages readers to engage with the content and follow future .NET Core publications.
Opinions
The author believes that understanding MongoDB is crucial before diving into the tutorial, suggesting readers familiarize themselves with it through a linked introductory post.
The author is considerate of the readers' varying levels of experience, providing detailed instructions for each step and assuming little to no prior knowledge in the setup and use of the tools and technologies mentioned.
The use of custom attributes for model validation indicates the author's preference for clean architecture and code maintainability.
By providing visual aids, such as screenshots and Gists for code snippets, the author demonstrates a commitment to clarity and ease of learning.
The invitation for questions and comments shows the author's interest in community engagement and support for readers' learning endeavors.
The author's enthusiasm for .NET Core is evident through the promotion of a dedicated .NET Core publication and related articles, suggesting a passion for sharing knowledge within the developer community.
Build a Web App with ASP.NET Core and MongoDB
In this post, I will show how to build a web application using ASP.NET Core MVC and MongoDB. If you are not familiar with MongoDB, you may want to read my Introduction to MongoDB post first.
Our application will manage a database of cars in a car gallery and its main page will look like below at the end.
I will use the following tools for application development:
I explained these instructions in detail in the Installation and Configuration section of the post that I mentioned above.
I am using Windows 10 so I will give the instructions for Windows.
1. Go to this site and download MongoDB for your OS version.
MongoDB is installed at C:\Program Files\MongoDB by default. In the C:\Program Files\MongoDB\Server\{version_number}\bin folder there are two executables: mongod and mongo.
2. Go to Control Panel -> System -> Advanced System Settings -> Environment Variables and edit Path variable and add C:\Program Files\MongoDB\Server\{version_number}\bin to that. This change enables MongoDB access from anywhere on your machine.
3. MongoDB’s default directory for data storage is /data/db. Create these directories in your C drive.
4. Open a command prompt and run the following command.
mongod
5. Open a new command prompt and run the below command:
mongo
We will run all our mongo shell methods in this command shell.
6. Run the following command:
use CarGalleryDb
This command creates the database if it does not exist. If it exists, its connection is opened for transactions.
7. Create a Cars collection using the following command:
db.createCollection('Cars')
Now, our database and collection are ready. We will perform CRUD operations on the Cars collection in the next sections.
Creating the ASP.NET Core MVC Project
Open File -> New -> Project..
Select ASP.NET Core Web Application and click Next.
In the next window, name the project and solution and click Create.
In the next window, select .Net Core and ASP.Net Core 2.2 as shown in the red box and select Web Application (Model-View-Controller) as project templateand then click Create.
Now, we will add the MongoDB driver to our project.
Right-click on the project and select Manage Nuget Packages…
In the Browse tab, search for mongodb and install the MongoDB.Driver:
In the Views/Shared/_Layout.cshtml file, make the following changes in the title, menu link and the footer.
Now, let’s run our project (Ctrl + F5) and see if everything is OK.
You can change the browser that you want to run the site from below:
After running, we get the Welcome page as below:
Adding a Model
Now, we will implement our data model class (Model part of the MVC app).
Right-click the Models folder and select Add->Class.
Give the name Car.cs to the class and click Add.
Then add the following properties to the class:
In the preceding class, the Id property:
is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
is annotated with [BsonId] to designate this property as the document’s primary key.
is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type string instead of ObjectId . Mongo handles the conversion from string to ObjectId.
Other properties in the class are annotated with the [BsonElement] attribute. The attribute’s value represents the property name in the MongoDB collection.
[YearRange] attribute is a custom attribute that allows only a valid range for the Year property. If you want to use this attribute, add CustomAttributes folder in the project as a new folder and add the following class there:
You can change the range as you want.
Adding a CRUD Services Class
In this section, we will addthe CarService class which uses the MongoDB.Driver members to perform CRUD operations against the database.
First, add a Servicesdirectory to the project root.
Then, add a CarService class to this directory with the following code:
Next, add the MongoDB connection string to appsettings.json:
The CarGalleryDb property is accessed in the CarService class constructor.
Now, let’s examine the CarService class:
The CarService class uses the following MongoDB.Driver members to perform CRUD operations against the database:
CarService.cs
MongoClient : Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string.
IMongoDatabase : Represents the Mongo database for performing operations. Generic GetCollection<T>(collection) method on the interface is used to gain access to data in a specific collection. CRUD operations can be performed against the collection after this method is called. In the GetCollection<T>(collection) method call:
collection represents the collection name in the database.
T represents the CLR object type stored in the collection.
GetCollection<T>(collection) returns a MongoCollection object representing the collection. The following methods are invoked on the collection:
Find<T> : Returns all documents in the collection matching the provided search criteria.
InsertOne : Inserts the provided object as a new document in the collection.
ReplaceOne: Replaces the single document matching the provided search criteria with the provided object.
DeleteOne: Deletes a single document matching the provided search criteria.
Registering the CarService with the Dependency Injection System
ASP.NET Core is built with Dependency Injection (DI). Services are registered with DI during application startup. Components that require these services are provided with these services via constructor parameters.
Now, we will register the CarService class with the Dependency Injection system.
Add the following code shown in the red box to the ConfigureServices method of Startup.cs:
Startup.cs
Now, let’s build the solution to check if everything is OK.
Adding a Controller
In this section, we will implement our controller (Controller part of the MVC app).
Right-click on the Controllers folder and select Add Controller…
In the Add Scaffold dialog, select MVC Controller with read/write actions :
Give CarsController as the name and then click Add.
Add the following highlighted code to the CarsController.cs:
In the next sections, we will implement controller methods and the views associated with them.
Index Method and View
Change the Index method in CarsController.cs as follows:
Then, right-click on the Indexmethod and select Add View…
Select the template and model class as shown below and click Add.
Cars folder and Index.cshtml are created in the Views folder after this operation:
Open the Index.cshml and make the following changes:
Remove the Id fields
Change the title Index to Car Gallery
Change Create New to Add New Car
Move the ImageUrl field to the up and change it to: