Using MongoDB .NET Driver with ASP.NET Core MVC

Before starting

This is a conversion of the original article Using MongoDB .NET Driver with .NET Core WebAPI to ASP.NET MVC. My intention would be to not repeat any of the points discussed there, and rather focus on how to have an ASP.NET Web App running.

To install

Here are all the things needed to be installed:

Project available in GitHub

Full source of this example is available on GitHub -> https://github.com/fpetru/mongodb-aspnetmvc. It includes creation of an ASP.NET Core Web Application, as well as copy of the existent code written. The project was creating by launching Visual Studio and then accessing menu: File > New Project > .Net Core > ASP.NET Core Web Application.

Run the sample project

After you have installed the required items, you would just need to have MongoDb server running, and to define the user credentials, to be able to access MongoDB. Once you have the credentials, write these settings in appsettings.json. You can find details on how to do this in the original article Using MongoDB .NET Driver with .NET Core WebAPI.

Then just compile and run from Visual Studio. From command line would be

dotnet restore
dotnet run

The page displayed in browser will look

Controller actions

Basically the change done is just in controller file (HomeController.cs), adding these actions.

public async Task Read()
{
	const string nodeId = "2";
	Note noteElement = await _noteRepository.GetNote(nodeId) ?? new Note();
	ViewData["Message"] = string.Format($"Note Id: {nodeId} - Body: {noteElement.Body}");

	return View();
}

public IActionResult Init()
{
	_noteRepository.RemoveAllNotes();
	_noteRepository.AddNote(new Note() { Id = "1", Body = "Test note 1", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, UserId = 1 });
	_noteRepository.AddNote(new Note() { Id = "2", Body = "Test note 2", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, UserId = 1 });
	_noteRepository.AddNote(new Note() { Id = "3", Body = "Test note 3", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, UserId = 2 });
	_noteRepository.AddNote(new Note() { Id = "4", Body = "Test note 4", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, UserId = 2 });

	ViewData["Message"] = string.Format($"Filled in 4 records");
	return View();
}

Unified frameworks

This conversion was very simple, due to fact that ASP.NET Core has unified the two frameworks, making it easy to build applications that include both UI (HTML) and APIs. Since they share the same code base and pipeline, the update was done just in the data is display, in the controller class.

Software developer, solution architect and technical lead.

Leave a reply:

Your email address will not be published.

Site Footer