Monday, December 26, 2016

Asp.Net MVC with MongoDB

In the Previous Posts I had shown
Now in this post I will show how to Connect with MongoDB using MongoDBCSharpDriver in Asp.Net MVC and retrieve data from MongoDB.


Create Application in MVC with any Name as you like, ones it is created ADD mongocsharpdriver from nuget as shown below.

Ones it is Added you can see the dll's as shown below.

MongoDB DataBase script file for this post Click Here 2 Download
Now create a class in Models Folder as shown below.

    public class Students
        public string _id { get; set; }
        public string SchoolName { get; set; }
        public string Class { get; set; }
        public string Name { get; set; }
        public List Subjects { get; set; }
        public double Year { get; set; }

In the web.config file ADD connection string as shown below

  <add name="MongoConString" connectionString="mongodb://"/><!--localhost-->

Now Build the solution, then replace the HTML code in Index.cshtml under Views/Home folder as shown below

@model IEnumerable<Mongo_School_MVC.Models.Students>
    ViewBag.Title = "Index";
    <h2>Students from School MongoDB</h2>
<div class="panel panel-default">
    <table class="table table-striped table-hover">
            <tr class="active">
                <th>School Name</th>
                <th>Student Name</th>
            @foreach (var item in Model)
                        @if (item.Subjects != null)
                            @String.Join(", ", @item.Subjects.Select(p => p).ToArray())
                        <input type="submit" formaction="" value="EDIT" class="btn btn-info btn-xs"  style="width:60px;"/>
                        <input type="submit"
                               value="Delete" class="btn btn-danger btn-xs"  style="width:60px;"/>

using MongoDB.Driver;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mongo_School_MVC.Models;

namespace Mongo_School_MVC.Controllers
    public class HomeController : Controller
        public MongoDatabase Database;
        public MongoCollection Collection;

        public HomeController()
            var client = new MongoClient(ConfigurationManager.ConnectionStrings["MongoConString"].ToString());
            var server = client.GetServer();
            Database = server.GetDatabase("School");

        public ActionResult Index()
            var rslt = Database.GetCollection("Students").FindAll().ToList();
            return View(rslt);

        public ActionResult About()
            ViewBag.Message = "Your application description page.";

            return View();

        public ActionResult Contact()
            ViewBag.Message = "Your contact page.";

            return View();

No comments:

Post a Comment