Showing posts with label Insert. Show all posts
Showing posts with label Insert. Show all posts

Friday, June 5, 2015

Posting Data to MongoDB using MVC5

Lets take an example of adding a book category to MongoDB

Create a controller and add action method to get the UI page so that user can enter the data

Add an Action Method
   [HttpGet]
        public ActionResult AddBookCategory()
        {
            return View("View1");
        }



add a Model
 public class BookCategory
    {
        public string CategoryName { get; set; }
    }
}

add a strongly typed View

This view contains text box control to add data and a submit button
we will use html helpers to use that

@model WebApplication1.Models.BookCategory

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View1</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal">
            <h4>BookCategory</h4>
            <hr />
            @Html.ValidationSummary(true)
   
            <div class="form-group">
                @Html.LabelFor(model => model.CategoryName, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CategoryName)
                  
                </div>
            </div>
   
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-primary" onclick="return confirm('This will insert category in the database')" />
                </div>
            </div>
        </div>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

and then again add a Action method inside a controller to insert into Mongo DB

[HttpPost]
        public ActionResult AddBookCategory(BookCategory category)
        {
           
            MongoClient monClient = new MongoClient("mongodb://localhost");
            MongoServer ms = monClient.GetServer();
            ms.Connect();
            MongoDatabase db = ms.GetDatabase("testdb");
            MongoCollection collection = db.GetCollection<BookCategory>("BookCategory");
            BookCategory bc=new BookCategory();
            bc.CategoryName=Request.Form["CategoryName"];
            collection.Insert(category);
            return View("View1");
          
        }
Isnt it simple . Try it out

Tuesday, November 11, 2014

Inserting to MongoDB from C#

I have always been a technology enthusiast and like to implement New things .
When I was introduced to mongo DB, an opensource database tool , I wondered how do I perform basic operations thru .Net .
Hence I created a simple application  .
Note : Mongo DB is NoSQL database and not Relational Database Like MSSQL or Oracle.

How I did it .

1.       Add MongoDb Dll Reference.
using MongoDB.Bson;
1.       using MongoDB.Driver;
2.       In the Button Click Event Create Mongo Connection
MongoClient monClient = new MongoClient("mongodb://localhost");
3.       Get Database name
       MongoServer ms = monClient.GetServer();
       ms.Connect();
MongoDatabase db = ms.GetDatabase("testdb");

Get Collections(tables)
MongoCollection collection = db.GetCollection<NewProjects>("Projects");

Add a new class similar to the structure u want the schema to be
public class NewProjects
{
       public NewProjects()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    public string ProjectName { get; set; }
    public string ServiceName { get; set; }
    public string DescriptionName { get; set; }

}

Assign Values to each field (Binding the values from Front End )
NewProjects proj=new NewProjects();
              proj.ProjectName=txtProjName.Text;
              proj.ServiceName=txtServiceName.Text;
       proj.DescriptionName=txtdesc.Text;

Finally Hit Insert Command
collection.Insert(proj);

View the Result in the backend database


Observe that Unique ID  is automatically Created .

Values Passed from Front End





PS: I know you may find it little strange to read Json like Documents(records) because Mongodb stores it in json format . so I have  converted these documents from Json like structure to Table format

Here we go




This application was build with Bootstrap JS