-->

Part 2 - How to fetch data from the database using angularjs in MVC4 application.

How to fetch data from the database using angularjs in MVC4 application.


Introduction

In this post, I would like to explain Part 2 - How to fetch data from the database using angularjs in MVC4 application.
This is our second Post about AngularJS. Here I have explained a little about AngularJS and What we will learn in this section part by part. In Part1 of this post we configured AngularJS in MVC4 application. In this part (Part 2) I am going to explain how to fetch data from the database using angularjs in MVC4 application.
Here In this example I will use AngularJS $http service. $http is an AngularJS service for reading data from remote servers.

Steps :

Step-1: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-2: Create table into the database.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-3: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
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 Namespace > Finish.

Step-4: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "DataController"

Step-5: Add new action into your controller for fetch data from Database and return as JsonResult.

Here I have added "GetLastContact" Action into "DataController". Please write this following code

            using System.Linq;
            using System.Web.Mvc;
            namespace MVCWithAngularJs.Controllers
            {
                public class DataController : Controller
                {
                    //
                    // GET: /Data/
                    //For fetch Last Contact
                    public JsonResult GetLastContact()
                    {
                        Contact c = null;
                        //here MyDatabaseEntities our DBContext
                        using (MyDatabaseEntities dc = new MyDatabaseEntities())
                        {
                            c = dc.Contacts.OrderByDescending(a => a.ContactID).Take(1).FirstOrDefault();
                        }
                        return new JsonResult { Data = c, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                    }
                }
            }

        

Step-6: Add a new js File for add a new AngularJS controller and a Factory

Go to Solution Explorer > Right Click on folder (where you want to saved your AngularJS controller files, here I have created a folder named "AngularController"  under Scripts Folder) > Add > Select Javascript file > Enter name > Add.

Write following code in this file.

            //here I am separating each angular controller to separate file for make it manageable 
            angular.module('MyApp') //extending from previously created angular module in the previous part
            .controller('Part2Controller', function ($scope, ContactService) { //inject ContactService
                $scope.Contact = null;
                ContactService.GetLastContact().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 = {};
                fac.GetLastContact = function () {
                    return $http.get('/Data/GetLastContact');
                }
                return fac;
            });            
        

Here I have created an angular controller named "Part2Controller" and a Factory named "ContactService" with $http injected service. I have explained a little about AngularJS controller here.
Factory : We can use factory 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 is an AngularJS service for reading data from remote servers. This support gives us the ability to make requests back and forth from a server or multiple servers, which is essential to a client-side app like ours that needs to get and set data. The $http service is a core AngularJS service that helps faciliate communication with remote HTTP servers via the XMLHttpRequest object or through JSONP.

Step-7: Add new action into your controller for Get the View for show data from database.

Here I have added "Part2" Action into "Home" Controller. Please write this following code

            public ActionResult Part2() // Fetch & Show Database Data
            {
                return View();
            }
        

Step-8: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
Complete View
            @{
                ViewBag.Title = "Part2";
            }

            <h2>Part2</h2>
            <div ng-controller="Part2Controller">
                <div style="font-weight:bold">
                    Contact Details
                </div>
                <table>
                    <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>

            @section scripts{
                <script src="~/Scripts/AngularController/Part2Controller.js"></script>
            }
        

Step-9: Run Application.


How to fetch data from the database using angularjs in MVC4 application.

Related Post : 


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.