Building application using ASP.NET MVC and MongoDB


This article talks about building a simple application using ASP.NET MVC and MongoDB. From my earlier blog post, the installation steps for Mongo DB were explained.

For building application using MongoDB and .NET, we need the 10gen C# Driver. This can be downloaded from http://github.com/mongodb/mongo-csharp-driver/downloads

Let’s began creating a simple ASP.NET MVC 3 application. We will be creating a simple application which will save the contact details and view the same.

The contact model is as show below
    public class Contact
    {
        [Required]
        [Display(Name = "Contact ID")]
        public int ContactID { get; set; }
    
        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Contact Number")]
        public string ContactNumber { get; set; }

        [Required]
        [Display(Name = "Contact Type")]
        public string ContactType { get; set; }
    }

We will add a View and call as “CreateContact”, the code for the same is as shown below




The Page will look as shown below





On Click of the “Save Contact” button, the data needs to be saved in the MongoDB. In the controller we will have to use the below references

using MongoDB.Driver;
using MongoDB.Bson;

The below code shows the saving process





In the “CreateContact”, we will set the server settings, get the instance the database and get the collection. We will create a BSON document object for the contact and add the data into the same. This is then inserted into the “Contacts” Collections using the “Insert” method.


For viewing the contacts, lets create a simple model for the same as shown below




    public class ViewContactModel
    {
        private List<Contact> _lstContact = null;
        public List<Contact> ContactList
 { get { return _lstContact; } set { _lstContact = value; } }
    }


We will add a new view “ViewContact”, the code is as shown below


Now lets add the code to the controller, to fetch the contacts from the database, the code is as shown below







We fetch the data by using the “FindAll()” method which is loaded into a contact object.


The output of the same is as shown below






This was a simple startup article which will get you started on working with ASP.NET MVCand MongoDB.


Hope this helps. Please leave your comments.

Comments

Nice simple example thanks.

Popular posts from this blog

Jesus - God Thinks of you.

ASP.NET 4.0 Feature - URL Routing

Tips on JQuery Intellisense in VS 2008