How to get Data from Database using Angular js in MVC 5 application ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Monday, 9 May 2016

How to get Data from Database using Angular js in MVC 5 application

22:03:00 Posted by raviteja swayampu , No comments
Hi every one i am very happy for your response for your previous post How to setup Angular js in ASP.NET MVC 5 application.In this tutorial i would like to explain How to get data from Database using Angular js in MVC 5 application.If your new to this angular tutorial please refer previous tutorial one it will really help you how to add angular files and configure angular js in MVC application.
In this example we are going to use $http service in Angular js. $http service in angular js is used to communicate with the remote servers for getting and setting data.In this example we are going to work on this service.

Step 1: Add a Database in application

1.In this tutorial i am using Sql Server Express(Local DB) for creating Table data.
2.Go to Solution explorer -->Right click on App_Data --> Add --> New Item -->Sql Server Data base under Data -->name it -->Add 


Step 2: Create Table in Database:

1.Open server explorer --> Expand Databasae 
2.Right click on Tables --> Add New Table -->Add columns into table and  Update database.
3.Table below columns in application.

creating new table in database

Step 3: Add Entity Data Model to application

1.Right click on Models -->Add --> New Item --> ADO.NET Entity Data Model --> name it --> Add.
2.A popup window will come (Entity Data Model Wizard) --> Select Generate from database -- > Next -- > Chose your data connection -- > select your database -- > next -- > Select tables -- > enter Model Name --> Click Finish.

ado.net entity data model in mvc5

Step 4: Create a Controller

1.Right click on Controllers -->Add --> Controller -->Select "Empty MVC Controller" -->Name it as HomeController.cs -->Add.

Step 5: Add new action into your controller for get data from Database

1.I added GetData() Json method to get fetch data from Database in HomeController
2.Add below code in HomeController.cs file
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HowtogetData_fromDatabaseusingAngular.Models;

namespace HowtogetData_fromDatabaseusingAngular.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetData()
        {
            MyDatabaseEntities db = new MyDatabaseEntities();

            Contact data = db.Contacts.OrderByDescending(x=>x.ContactID).Take(1).FirstOrDefault();

            return new JsonResult { Data = data, JsonRequestBehavior=JsonRequestBehavior.AllowGet};
        }
       
    }
}

3.Here,Index action is to render view(Index View).

Step 6: Add new script file to Add Angular js code

1.Right click Scripts --> Add --> Java script file -->name it
2.Add below code there.i named the file as myscript.js


(function () {
    //Create a Module 
    var app = angular.module('MyApp', ['ngRoute']);  // Will use ['ng-Route'] when we will implement routing
    //Create a Controller
    app.controller('HomeController', function ($scope) {  // here $scope is used for share data between view and controller
        $scope.Message = "welcome to angular js";
    });
})();

3.Here i created a angular application "MyApp" and angular controller "HomeController".The angular module initializes angular application.
4.Now add another Java script file (i named it myscript2.js).
angular.module('MyApp') //extending from previously created angular module MyApp
    //another controller we can add many controllers to angular application
.controller('Part2Controller', function ($scope, ContactService) { //inject ContactService
    $scope.Contact = null;
    ContactService.GetData().then(function (d) {
        $scope.Contact = d.data; // Success
    }, function () {
        alert('Failed'); // Failed
    });
})
.factory('ContactService', function ($http) { // here I have created a factory which is a populer way to create and configure services
    var fac = {};                               //using factory method i am configuring service.
    fac.GetData = function () {
        return $http.get('/Home/GetData');      //gets data from GetData Action in HomeController
    }
    return fac;
});

Here, a ContactService with contacts with server for data.And gets data as a response from server. ContactService is an $http angular service.

Factory : Factory metnod is to organize and share code across our app. Its moreover same like Service Layer of our asp.net application, where we write reusable code for share across our application.

#http: $http service is angular service that have ability to contact with remote servers to get and set data from server.We can make requests to multiple servers.$http is angular js core service essential for client side applications to access remote data. It communicates with remote servers using XMLHTTPRequest object.

step 7: Add View to Display Data

1.Right click Index View --> Add View --> Add.
2.replace index view code with following code.

@{
    ViewBag.Title = "Getting Data from DB using Angular";
}
<div ng-controller="Part2Controller">
        <h3 class="text-info">Contact Details</h3>
    <div class="container">
        <table class="table table-responsive table-bordered">
            <tr>
                <td>First Name :</td>
                <td>{{Contact.FirstName}}</td>
            </tr>
            <tr>
                <td>Last Name : </td>
                <td>{{Contact.LastName}}</td>
            </tr>
            <tr>
                <td>Contact No1:</td>
                <td>{{Contact.ContactNo1}}</td>
            </tr>
            <tr>
                <td>Contact No2:</td>
                <td>{{Contact.ContactNo2}}</td>
            </tr>
            <tr>
                <td>Email ID:</td>
                <td>{{Contact.EmailID}}</td>
            </tr>
            <tr>
                <td>Address</td>
                <td>{{Contact.Address}}</td>
            </tr>
        </table>
    </div>
</div>
@section scripts{
    <script src="~/Scripts/myscript2.js"></script>
}

Finally we displayed data using {{data}} Angular expressions like above.
Run application Press F5
we get,

How to get data from DB using Angualar js

Download Source code from here Downlaod
You may also like these


Conclusion:
Thank you for viewing this please subscribe to this site for daily updates.Please recommend any modifications if you want i hope you understand this tutorial. You will find more tutorials and code samples from this site.


0 comments:

Post a Comment