Friday, April 29, 2016

WebApi with MongoDB. HttpPost

Create an api controller. and write Post method. since there is no mongodb collection yet but thru post you can create a collection and fill the documents on the fly






public void Post(Categories categories)


        {


            var connectionString = "mongodb://localhost:27017";




            MongoClient client = new MongoClient(connectionString);


            MongoServer _mongoServer = client.GetServer();


            _mongoServer.Connect();


            MongoDatabase mongodatabase = _mongoServer.GetDatabase("testdb");


            MongoCollection collections = mongodatabase.GetCollection<Categories>("Categories");


            Categories cat = new Categories();


            cat.DepartmentName = categories.DepartmentName;


            try


            {


                collections.Insert(cat);


            }


            catch (Exception ex)


            {


                throw new Exception(ex.Message.ToString());






            }


          




        }


Create an html page .
Add HTML  controls
make an ajax call to api controller thru angular



<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>

    <link href="Content/bootstrap.css" rel="stylesheet" />

</head>

<body ng-app="DocOnlineModule">

    <form ng-submit="submiting()" ng-controller="CategoriesController">


        <div class="text-center" style="padding:50px 0">

            <div class="form-group">

                <label for="txtcat">Category name</label>


                <input type="text" class="form-group-sm" id="txtcat" ng-model="DepartmentName" placeholder="CategoryName" />

                <div>

                    <input type="submit" class="btn btn-primary" id="EmployeeSUbmit" value="submit" />

                </div>

            </div>

        </div>

        <script>

            angular.module("DocOnlineModule", [])

            .controller("CategoriesController", ['$scope', '$http', function ($scope, $http) {


                $scope.submiting = function () {


                    var Cats = {

                        "DepartmentName": $scope.DepartmentName,




                    }

                    $http.post('http://localhost:59413/api/Categories', Cats).

                    success(function (data) {

                        alert('cats added successfully');

                    }).error(function (data, status) {

                        alert(status);

                    });




                }



            }]);

        </script>



    </form>


</body>

</html>

Run the solution