Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Creating ASP.NET MVC application with AngularJS


I have already shared post on AngularJS with CRUD operations but in this post I am going to share Basic example that retrieves data from database and display it using AngularJS, MVC and Entity framework.


AngularJS is a JavaScript framework open-source client-side web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Following are some angular directives I used in this example:


Declares the root element of an AngularJS application, under which directives can be used to declare bindings and define behavior.


Specifies a JavaScript controller class that evaluates HTML expressions.


Instantiate an element once per item from a collection.

AngularJS with ASP.NET MVC Example

In layout section I added reference to angularJS controller,service code.


<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <script src=""></script>
    <script src="~/Content/js/AngApp.js"></script>
    <script src="~/Content/js/Employee.js"></script>
    <script src="~/Content/js/Service.js"></script>
    @RenderSection("scripts", required: false)
</html> MVC View and AngularJS View

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
 <div ng-app="EmpApp" ng-controller="EmpCntrlr">
        <table border="1" cellpadding="10" align="center" class="table table-bordered table-striped">
                    Employee Id
                    Employee Name
                    Email Id
            <tr ng-repeat="emp in employees|orderBy :'Name'">
         </div> Entity framework and Model


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AngularMvcApp.Models
    public class EmolyeeDbContext : DbContext
        public EmolyeeDbContext()
            : base("DefaultConnection")
        { }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        public DbSet<EmployeeData> EmployeeData { get; set; }
} Employee Model


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; 
namespace AngularMvcApp.Models
    public class EmployeeData
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
} MVC Controller

using AngularMvcApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularMvcApp.Controllers
    public class HomeController : Controller
        // GET: /Home/
        public ActionResult Index()
            return View();
        // GET: All Employees
        public JsonResult GetAllEmployees()
            using (EmolyeeDbContext contextObj = new EmolyeeDbContext())
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);


AngularJS Model

var app = angular.module("EmpApp", []);

AngularJS Controller

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    function GetAllEmployee() {
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees =;
        }, function () {
            alert('Employee data not found');

AngularJS Service

app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        return $http.get("/Home/GetAllEmployees");

Group Query Results using LINQ


Grouping on data is common requirement in finance and data applications, programmers write Frequently code to perform these operations. In old applications architects prefer grouping logic in database programming only and they use front end coding to display grouped data.

              Now LINQ provides easier and faster approach to query over data using LINQ to entities and LINQ to Data-set.

In this article I will explains in detail,

  a. How I can Group data using LINQ?
  b. How I can group data with multiple columns using lambda?
  c. How I can group data with multiple columns using linq but not using any extension method? 

Group by in LINQ

Grouping is one of the most powerful capabilities of LINQ. In this example I will explain grouping using LINQ with following sample examples.

            1.   Groping List data with single property.
       2.   Grouping List data with multiple properties.
       3.   Grouping Data Table data with single columns.
       4.  Grouping Data Table data with multiple columns.
       5. Grouping Data with Bool Value

You can perform grouping using group clause and GroupBy() extension method same I performed with following examples.

group clause

The group clause returns a sequence of IGrouping<TKey, TElement> objects that contain zero or more items that match the key value for the group.

GroupBy() Method

Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

Groping List data with single property

Using group clause (Grouping by string)

The following example shows how to group source elements by using a single property of the element as the group key. In this case the key is a string “UserName”.

  var GroupUserByNames =
                from user in activeUsers
                group user by user.UserName;

Using Group by Method

The following example shows how to use GroupBy() extension method to group results with single property. In this case the single group property is the UserName.

List<User> CheckDuplicateUsers= activeUsers.GroupBy(U => 
                 U.UserName).Where(gr => gr.Count() > 1).SelectMany(dupRec => dupRec).ToList();

Grouping List data with multiple properties

Using group clause (Group data by numeric range)

In this example we used expression to create numeric group keys that represent a percentile range. Note the use of let as a convenient location to store a method call result, so that you do not have to call the method two times in the group clause.

     var GroupProductByProfit=from product in products
      let profitPercentage=GetProductProfit (product)
      group new { product.Name, product.Type } by profitPercentage into ProfitPercentGroup orderby ProfitPercentGroup.Key
      select ProfitPercentGroup;

Using Group by Extension Method

          List<BasicProduct> CheckDuplicateProducts = activeProducts.GroupBy(u =>
                 new { productCode=u.ProductCode,Type=u.ProductType}
            ).Where(gr => gr.Count() >1).SelectMany(dupRec => dupRec).ToList();

Grouping Data Table data with single columns:

Using group clause

Following example explains how to use group by clause to group data with single column value (key value).

var GroupUserByNames = from user in UsersTablle.AsEnumerable()
                group user by Field<string>("UserName") into newGroup
                orderby newGroup.Key
                select newGroup;

Using Group by Extension Method

Following example explains how to use GrouBy() method to group data with single column value (key value).

DataTable duplicatesUsers =UsersTablle.AsEnumerable().GroupBy(x
=> x.Field<string>("UserName"))
    .Where(gr => gr.Count() >1).SelectMany(dupRec => dupRec).ToList().CopyToDataTable();


Grouping Data Table data with multiple columns   

Using group clause (Grouping by Composite Keys)

Use a composite key when you want to group elements according to more than one key. You create a composite key by using an anonymous type or a named type to hold the key element.

In this example grouping is performed with two composite keys name and address.

var GroupUserByNames =
                from user in UserTable.AsEnumerable()
                group user by new
                    Name = user.Field<string >("Name"),
                    Address = user.Field< string >("Address")
                } into newGroup
                orderby newGroup.Key
                select newGroup;

Using Group by Extension Method

  //LINQ query retrieves duplicate records from data table
on two columns and save result in another table
        DataTable resultTable = Data.AsEnumerable()
                          .GroupBy(row => new
                              UserName = row.Field<string>("UserName"),
                              OrignalAuthor = row.Field<string>("OrignalAuthor")                           }).Where(gr => gr.Count() > 1).SelectMany(dupRec => dupRec).ToList().CopyToDataTable();


Grouping Data by using Bool Value

Following example group employees those eligible for taxable income and not eligible for taxable income, Grouping is performed with bool values.

  // Group by true or false.
   Var GroupEmployeByPackage=
        from employee in employees
       group employee by employee.package >=500000;//taxable or nontaxable!


 धन्यवाद मित्रानोआपला प्रत्येक दिवस आनंदी आणि सुखी जावो  

AngularJS Routing


When I started writing on AngularJS I shared following tow posts on AnjularJS

In both posts I mentioned AngularJS is a Single Page Applications(SPA) framework,

I think that is a wrong assumption you can use AnjularJS for creating multi page applications also easily and efficiently.

AngularJS is a Single Page Applications (SPA) framework is only Hype?

AngularJS does not enforce developers to create SPAs. It makes it easy to write SPAs, hence people created hype about AngularJS it is Single Page Applications (SPA) framework.

You can create easily AngularJS choose Multi Pages Applications (MPAs) using $Route Module,routing service provider $routeProvider, ng-View directive and  inbuilt AngularJS Dependency Injection feature.

Always choosing single page application is not good- especially if you are looking into highly complex, Module based, pluggable UI architecture in that case my suggestions Is choose Multi Pages Application (MPA).

MPAs Required Terms Explained:

ngRoute Module

The ngRoute module provides routing and deeplinking services and directives for angular apps.


angular.module('YourModule', ['ngRoute'])


Provider is Used for configuring routes, Requires the ngRoute module to be installed.
Application routes in Angular are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.


$route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition

The $route service is typically used in conjunction with the ngView directive and the $routeParams service.

 ng-View Directive

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.


  <[html tag]  ng-view>your html view code</[html tag]>

AngularJS Multi Pages Application Example

I will create sample AngularJS application with two views,

1. employee.html

2. contact.html

And I will explain this example following steps.

Step 1:

A. Create a module named mainApp and load ngRoute as a dependent module.

B. Configure the routes using $routeProvider.

C. We use three paths in the example, /home ,/viewEmplyees,/viewContacts with EmployeeController and

    ContactController this is initialized with an array of employees and a contact message.

E. We will be showing the message in the home page and the employees list in employee page, and contact details in contact page.

F. Save this file as AppRouteExample.js.

AngularJS Controller and Model code

var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(function ($routeProvider) {
        .when('/home', {
            templateUrl: 'home.html',
            controller: 'EmployeeController'
        .when('/viewEmployees', {
            templateUrl: 'employees.html',
            controller: 'EmployeeController'
        .when('/viewContacts', {
            templateUrl: 'contact.html',
            controller: 'ContactController'
            redirectTo: '/home'
mainApp.controller('EmployeeController', function ($scope) {
    $scope.employees = [
        { name: 'Shourya Kendre',designation:'CEO',company:'CodeChef4u', city: 'Pune' },
        { name: 'Sanskruti Kendre', designation: 'Director', company: 'Aditya Enterprises', city: 'Riagad' },
        { name: 'Anushka Kendre', designation: 'Chairman', company: 'KCS', city: 'Latur' }
    $scope.message = "Click on the hyper link to view the employess list.";
mainApp.controller('ContactController', function ($scope) {
    $scope.message = 'Please contact us at contact page or';

Step 2:

Now we can create our views and save as home.html, employee.html, contact.html


<div class="container">
          <div class="row">
          <div class="col-md-3">
              <ul class="nav">
                  <li><a href="#/viewEmployees"> View Employees List</a></li>
                  <li><a href="#/viewContacts"> Contact Us </a></li>


<div class="container">
    <h2> View Employees </h2>
        <input type="text" ng-model="name" />
        <li ng-repeat="employee in employees | filter:name">{{}},{{employee.designation}} ,{{}}, {{}}</li>
    <a href="#/home"> Back</a>


<div class="container">
 <a href="#/home"> Back</a>

Step 3:

1. The ng-app  auto-bootstraps our application mainApp

2. The ngView directive is the placeholder of the views ( home.html, employee.html and contact.html).

3. Include angular.min.js and angular-route.min.js

4. Include AppRouteExample.js which we have created in the first step.

5. Save the file as index.html


<!DOCTYPE html>
    <head lang="en">
      <meta charset="utf-8">
      <title>AngularJS Routing</title>
        <script src="Content/js/angular.min..js"></script>
        <script src="Content/js/angular-route.js"></script>
        <script src="Content/js/AppRouteExample.js"></script>
      <div ng-app="mainApp">

Step 4

Save all files in same location.

Open index.html with your browser or type the URL in your browser, For example: yourLocationURL/index.html

 धन्यवाद मित्रानोआपला प्रत्येक दिवस आनंदी आणि सुखी जावो