Wednesday, August 26, 2015

Insert data In Angularjs And Asp.Net MVC 4

Insert data In Angularjs And Asp.Net MVC 4

In this blog, I’m explaining how to insert data in the database using angular js and asp.net mvc 4.

Step 1:

First create a table in database named “Student” like this:



Step 2:

Now create a basic asp.net mvc 4 application and add database connection like this:




Step 3:

Now add a controller named “HomeController” and add following code in it:


using CRUDInAngulaJsMvcApp.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CRUDInAngulaJsMvcApp.Controllers
{
    public class HomeController : Controller
    {
        AngularJsEntities db = new AngularJsEntities();

        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Add(Student newStudent)
        {

            db.Students.Add(newStudent);
            db.SaveChanges();
            return Json(new { Status = "Successfull" }, JsonRequestBehavior.AllowGet);

        }
    }
}

Step 4:

Now add Index view and write the following code:


@model List<CRUDInAngulaJsMvcApp.Database.Student>
@{
    ViewBag.Title = "Index";
}

<h2>Student Details</h2>

@Html.ActionLink("Add", "Add", "Home")

<br />
@foreach(var item in Model)
{
    <div style="width:20%;display:inline-block;">
        <p>Name : @item.Name</p>
        <p>City : @item.City</p>
        <p>Course : @item.Course</p>
        <p>Mobile : @item.Mobile</p>
    </div>
  
}

Step 5:

Now add another view named “Add” and write the following code in it:

@{
    ViewBag.Title = "Add";
}
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/App/Add.js"></script>
<h2>Add</h2>

<form>
    <div ng-app="addModule" ng-controller="AddController">
        Name : <input type="text" ng-model="Name" />
        <br />
        <br />
        City : <select ng-model="City" ng-options="city as city for city in Cities"></select>
        <br />
        <br />
        Course : <select ng-model="Course" ng-options="course as course for course in Courses"></select>
        <br />
        <br />
        Mobile : <input type="text" ng-model="Mobile" />
        <br />
        <br />
        <input type="button" ng-click="add()" value="Add" />
    </div>
</form>

Step 6:

Now create a javascript file named “Add.js” and write the code in it:


//First create the angular module and named it "addModule"
var addModule = angular.module("addModule", []);

//Create a factory service
addModule.factory('AddRecordService', ['$http', function ($http) {
    return {

        //Get the courses list
        getCourse: function(){
            return ["Btech", "BCA", "BBA", "MTech", "MCA", "MBA"]
        },

        //Get the city list
        getCity: function(){
            return ["New York", "Los Angeles", "Paris", "Tokyo", "Sydney", "New Delhi"]
        },

        //This function will call the add action in the homecontroller and save the data in the database
        saveRecord : function(newStudent)
        {
            $http({
                url: '/Home/Add',
                method: 'POST',
                data : newStudent
            }).then(function (response) {
                if (response !== 'undefined' && typeof (response) == 'object') {
                    window.location.href = '/Home/Index';
                }
            });
        }
    };
}]);


//Create controller with the dependencies
addModule.controller('AddController', ['$scope', '$http', 'AddRecordService', function ($scope, $http, AddRecordService) {

    $scope.Courses = AddRecordService.getCourse();
    $scope.Cities = AddRecordService.getCity();
    $scope.showMessage = false;

    $scope.add = function () {
        var newStudent = {};
        newStudent["Name"] = $scope.Name;
        newStudent["City"] = $scope.City;
        newStudent["Course"] = $scope.Course;
        newStudent["Mobile"] = $scope.Mobile;

        AddRecordService.saveRecord(newStudent);
    }


}]);


Output

Run the application:


This will show the existing data in the table, click on add button:



Fill the form and click on Add button:








Tuesday, August 25, 2015

Form and Ng-Submit in Angular Js

Form and Ng-Submit in Angular Js

In this blog, I’m explaining how to create a form and submit it using the angular js.

Example


First create an index.html page and the reference of angular.min.js file like this:


<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Ngsubmit</title>
   <script src="~/Scripts/angular.min.js"></script>
<body>
</body>
</html>


Now add the <script> tag in the head section of the page write the following code:

<script>
        var app = angular.module("myApp", []);

        app.controller("myController", function ($scope) {
            $scope.names = [{ name: "Sumit" }];

            $scope.addValue = function () {
                $scope.names.push($scope.newData);
                $scope.newData = '';
            }
        });

    </script>


Here I have create the controller named “myController”, and it has one property names which is an array and a method addValue() : used to add the value in the names.


Now in the <body> tag :

<body ng-controller="myController as ctrl">
    <div>
        <div>
            <ul>
                <li ng-repeat="n in names">{{$index + 1}} - {{n.name}}</li>
            </ul>
            <p>Total Entry : {{names.length}}</p>
        </div>
        <div>
            <form ng-submit="addValue()">
                <input type="text" ng-model="newData.name" />
                <input type="submit" value="add" />
            </form>
        </div>
    </div>
</body>


In the <body> add the “myController” controller using the ng-controller directive.

Ng-repeat directive will display all the values in the names.

$index will show the index of the object in the array. It starts with 0.

In the angular expression, names.length will display the total number of objects in the array.

Ng-submit directive will submit the form to the addValue() method.

Output

Run the application:



Enter any name in the textbox and click on add button:






This will add the name in the array.


My Previous Blogs: