Website Development in ASP.NET Core with MongoDB

Developing a website using ASP.NET Core with MongoDB is a great choice for modern web applications. Below is a step-by-step guide to help you get started.

Step 1: Set Up Your Development Environment

  1. Install .NET SDK: Download and install the latest version of the .NET SDK from the official .NET website
  2. Install MongoDB: You can either install MongoDB locally or use a cloud service like MongoDB Atlas. For local installation, follow the instructions on the MongoDB installation page.
  3. Install Visual Studio / Visual Studio Code: For development, you can use either Visual Studio or Visual Studio Code. Visual Studio provides a more integrated experience, while Visual Studio Code is lightweight and highly extensible.

Step 2: Create a New ASP.NET Core Project

  1. Open the Visual Studio and click on the Create a new project.
  2. The Create a new project window will appear.
    • Find the ASP.NET Core Web App (Razor Page) template.
    • Select the template and click on the Next button.
  3. Then Configure your new project window will appear.
    • Give the name RazorWeb to your project.
    • Click on the Next button.
  4. Additional information windows will be displayed.
    • Select .Net 8.0 as framework.
    • Uncheck the Do not use top-level statements if checked.
    • Click on the Create button.
  5. You are done with ASP.NET Core Web APP template.

Step 4: Create MongoDB Model.

We will create a model to store and retrieve data from back-end data stores. Follow the steps to create a model in ASP.NET Core Web API.

  1. Add a directory with the name Models to the project root.
  2. Add a StudentMaster class to the Models directory with the following code:
     using MongoDB.Bson;  
     using MongoDB.Bson.Serialization.Attributes;  
     namespace ManageSchoolAPI.Models;  
     public class StudentMaster  
     {  
       [BsonId]  
       [BsonRepresentation(BsonType.ObjectId)]  
       public string? ID { get; set; }  
       [BsonElement("Name")]  
       public string StudentName { get; set; } = null!;  
       public string RollNumber { get; set; }  
       public string Division { get; set; } = null!;  
       public string Standard { get; set; } = null!;  
     }  
    
  3. In the preceding class, ID is required to map the Common Language Runtime (CLR) object to the MongoDB collection and the attributes are:
    • BsonId to make this property the document's primary key.
    • Annotated with BsonRepresentation(BsonType.ObjectId) to allow passing the parameter as type string instead of an ObjectId structure. Mongo handles the conversion from string to ObjectId.
  4. The StudentName property is annotated with the BsonElement attribute. The attribute's value of Name represents the property name in the MongoDB collection

Step 5: Configure MongoDB Connection

  • Add the following database configuration values to appsettings.json:
     {  
       "SchoolDatabase": {  
         "ConnectionString": "mongodb://localhost:27017",  
         "DatabaseName": "SchoolManagement",  
         "StudentCollectionName": "StudentMaster"  
       },  
       "Logging": {  
         "LogLevel": {  
           "Default": "Information",  
           "Microsoft.AspNetCore": "Warning"  
         }  
       },  
       "AllowedHosts": "*"  
     }  
    
  • Add a SchoolDatabaseSettings class to the Models directory with the following code, the class is used to store the appsettings.json file's SchoolDatabase property values. The JSON and C# property names are named identically to ease the mapping process.
     namespace ManageSchoolAPI.Models;  
     public class SchoolDatabaseSettings  
     {  
       public string ConnectionString { get; set; } = null!;  
       public string DatabaseName { get; set; } = null!;  
       public string StudentCollectionName { get; set; } = null!;  
     }  
    
  • The following code is the configuration instance to which the appsettings.json file's SchoolDatabase section binds is registered in the Dependency Injection (DI) container. For example, the SchoolDatabaseSettings object's ConnectionString property is populated with the SchoolDatabase:ConnectionString property in appsettings.json. add this code in the program.cs file after instance of web application and take reference of Models namespace.
     var builder = WebApplication.CreateBuilder(args);  
     // Add services to the container.  
       builder.Services.Configure<SchoolDatabaseSettings>(  
       builder.Configuration.GetSection("SchoolDatabase"));  
    

Step 6: Add MongoDB as Service

  • Add a Services directory to the project root.
  • Add a MongoDB Service class to the Services directory with the following code:
     using ManageSchoolAPI.Models;  
     using Microsoft.Extensions.Options;  
     using MongoDB.Driver;  
     namespace ManageSchoolAPI.Services;  
     public class MongoDBService  
     {  
       private readonly IMongoCollection<StudentMaster> _studentCollection;  
       public MongoDBService(  
         IOptions<SchoolDatabaseSettings> schoolDatabaseSettings)  
       {  
         var mongoClient = new MongoClient(  
           schoolDatabaseSettings.Value.ConnectionString);  
         var mongoDatabase = mongoClient.GetDatabase(  
           schoolDatabaseSettings.Value.DatabaseName);  
         _booksCollection = mongoDatabase.GetCollection<StudentMaster>(  
           schoolDatabaseSettings.Value.StudentCollectionName);  
       }  
       public async Task<List<StudentMaster>> GetAsync() =>  
         await _studentCollection.Find(_ => true).ToListAsync();  
       public async Task<StudentMaster?> GetAsync(string id) =>  
         await _studentCollection.Find(x => x.Id == id).FirstOrDefaultAsync();  
       public async Task CreateAsync(StudentMaster newStudent) =>  
         await _studentCollection.InsertOneAsync(newStudent);  
       public async Task UpdateAsync(string id, StudentMaster updatedStudent) =>  
         await _studentCollection.ReplaceOneAsync(x => x.Id == id, updatedStudent);  
       public async Task RemoveAsync(string id) =>  
         await _studentCollection.DeleteOneAsync(x => x.Id == id);  
     }  
    
  • Register the MongoDB Service by adding following code in program.cs file, use the Services namespace after adding the code.
     var builder = WebApplication.CreateBuilder(args);  
     // Add services to the container.  
     builder.Services.Configure<StudentDatabaseSettings>(  
       builder.Configuration.GetSection("StudentDatabase"));  
     builder.Services.AddSingleton<MongoDBService>();  
    

Step 7: Create Pages to Perform CRUD Operations

This section will ASP.NET Razor produces pages for Create, Read, Update, and Delete (CRUD) operations for the student model by scaffolding the student model class.

  1. Create the Pages/Movies folder:
    • Right-click on the Pages folder > Add > New Folder.
    • Name the folder Students.
  2. Right-click on the Pages/Students folder > Add > New Scaffolded Item.
  3. In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.
  4. Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
    • In the Model class drop down, select Movie (RazorWeb.Models).
    • In the Data context class row, select RazorWeb database context if not automatically selected.
    • Click on Add button.
  5. The page creation process will start, and you will notice below five cshtml files will be created in the students folder with their Page model classes after the process completed.
    • Create
    • Delete
    • Details
    • Edit
    • Index

Run the project, make sure there is no error. if the project successfully run then follow steps below for creatin a menu in home page to access the index page of Student entity to perform CRUD operations

  • In the Solution Explorer, Find the Shared folder and expand it.
  • Double click on the _Layout.cshtml file to open it.
  • Fine the UL element, the UL element looks like below
     <ul class="navbar-nav flex-grow-1">  
    
  • Add the below LI element at end of the UL element.
      <li class="nav-item">  
        <a class="nav-link text-dark" asp-area="" asp-page="/Students/Index">Students</a>  
      </li>  
    

Run the project again. the home page will be appear in the browser. Click on the Students menu resides near the Privacy menu. Browser will redirect to the Index page of Student, perform the CRUD operation

I hope that the steps explained here in the post (Website Development in ASP.NET Core with MongoDB) are helpful to develop a website in ASP.Net Core with basic functionalities.

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

1 Comments

Previous Post Next Post

نموذج الاتصال