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

No comments:

Post a Comment