Retrieving a collection of objects with page methods and AngularJS in ASP.NET Web form

Page Methods are asp.net web form feature. It is an easy way to communicate with the server. You can communicate with server using Page Methods and can do anything you like but mind it is not restful form of communication. In this solution I used visual studio 2012 and bootstrap. So let’s start to retrieve a collection of objects with Page Methods and AngularJS in ASP.NET web forms.

Step 1: Create a ASP.NET Web Forms Application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET Empty web application, set location and click OK

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package AngularJS.Core
PM> Install-Package AngularJS.Resource
PM> Install-Package bootstrap

Step 3: Design Master Page

Add required references for bootstrap and AngularJS and design master page using bootstrap as follows.
You can use theme. For details visit the article “ Easy way to design web layout by bootstrap theme


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebMathodAngular.Site" %>





    

    
    

    
    


    
    

Here you must see that I used the reference of app.js, data.js. studentCtrl.js which are not defined yet. Soon, I will create those files. Another thing that you must set EnablePageMethod=”True”

Step 4: Create Application module, data and angular controller
Create app.js, data.js and studentCtrl.js in scripts -> app folder. Content are given below.

app.js

var app = angular.module('app', ['ngResource']);

data.js

app.value('pageMethods', PageMethods);

app.factory('student', function (pageMethods, $rootScope) {
    var result = [];
    pageMethods.GetStudent(function (data) {
        data.forEach(function (item) {
            result.push({ id: item.Id, name: item.Name, semester: item.Semester, credits: item.Credits});
        });
        $rootScope.$apply();
    });
    return result;
})

studentCtrl.js

app.controller('studentsCtrl', function ($scope, student) {
    $scope.student = student;
});

Here, App.js for just declaring application module, data.js for retrieving data using Page Methods and studentCtrl.js is the main angular controller. You must see, in data.js I have declare pageMethods and call a Page Method name “GetStudent”. This is not yet defines. I will create this method in next Step.

Step 4: Create a Page for View

Create a page name Default.aspx, just right click on the application -> Add -> New item -> Web form using master page. Select Master page and type page name as Default.aspx. Now modify the page as follows.

Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebMathodAngular
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static List GetStudent()
        {
            List lstStudents = new List()
                {
				new Student { Id= 1, Name= "Mahedee Hasan", Semester="5th", Credits= 15},
				new Student { Id= 2, Name= "Robiul Alam", Semester="4th", Credits= 20},
				new Student { Id= 3, Name= "Amit Karmaker", Semester="7th", Credits= 12 },
				new Student { Id= 4, Name= "Zahid Hasan", Semester="8th", Credits= 18},
				new Student { Id= 5, Name= "Shafiqul Islam", Semester="6th", Credits= 15},
				
			};

            return lstStudents;
        }


    }


    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Semester { get; set; }
        public int Credits { get; set; }
    }

}

In Deafult.aspx.cs file, you must see I have created a Page Method which is annoted by WebMethod. This method returns a list of Students object.

Default.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebMathodAngular.Default" %>




    
Id Name Credit Semester
{{student.id}} {{student.name}} {{student.credits}} {{student.semester}}

Look at the page, here I add ng-controller and ng-app and ng-repeat. If you have little idea about angularJs, you must understand the page. Now just run the application and you will get following output.

Output

*If you don’t clear in any portion or any suggestion, please leave your comment here. To run the application download required packages.

Introduction to AngularJs and Bootstrap in ASP.NET Web form

Revolution just arrived. Client side development is getting easier and cheaper. AngularJs is one of the client side development JavaScript framework. It is developed by google. Website designing also get easier due to emerge of bootstrap. Now let’s introduce AngularJS and Bootstrap in a asp.net web form application. Here I used visual studio 2012 as an IDE.

Step 1: Create a ASP.NET Web Forms Application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET Empty web application, set location and click OK

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package AngularJS.Core
PM> Install-Package AngularJS.Resource
PM> Install-Package bootstrap

Step 3: Design Master Page

Add required references for bootstrap and AngularJS , and design master page using bootstrap as follows.
You can use theme. For details visit the article “ Easy way to design web layout by bootstrap theme


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="AngularWeb.Site" %>





    

    
    

    
    


    
    

Here you must see that I used the reference of app.js, data.js. studentCtrl.js which are not defined yet. Soon, I will create those files.

Step 4: Create Application module, data and angular controller
Create app.js, data.js and studentCtrl.js in scripts -> app folder. Content are given below.

app.js

var app = angular.module('app', ['ngResource']);

data.js

app.value('studentInfo', [
  { id: 1, name: 'Mahedee Hasan', credit:20, semester: '8th' },
  { id: 2, name: 'Enamul Haque', credit: 15, semester: '7th' },
  { id: 2, name: 'Arefin Billah', credit: 15, semester: '6th' },
  { id: 3, name: 'Zahid Hasan', credit: 12, semester: '7th' }
]);

studentCtrl.js

app.controller('studentsCtrl', function ($scope, studentInfo) {
    $scope.studentInfo = studentInfo;
});

App.js for just declaring application module, data.js for hardcoded data by javascript and studentCtrl.js is the main angular controller.

Step 4: Create a Page for View

Create a page name Default.aspx, just right click on the application -> Add -> New item -> Web form using master page. Select Master page and type page name as Default.aspx. Now modify the page as follows.


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AngularWeb.Default" %>




 
   
Id Name Credit Semester
{{student.id}} {{student.name}} {{student.credit}} {{student.semester}}

Look at the page, here I add ng-controller and ng-app and ng-repeat. If you have little idea about angularJs, you must understand the code. Now just run the application and you will get following output. Happy programming.

Output

*If you don’t clear in any portion or any suggestion, please leave your comment here. To run the application download required packages.

JSON Serialization in ASP.NET MVC and AngularJs

In this article I will show how JSON serialize in ASP.NET MVC and bind data by AngularJs. I will not describe what and how JSON, ASP.NET MVC or AngularJs work. Hope I will discuss these topics in another article.
Let’s start to create an ASP.NET MVC project with AngularJs.

Step 1: Create ASP.NET MVC application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine

Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package.


PM> Install-Package jQuery
PM> Install-Package angularjs -Version 1.2.26
PM> Install-Package Newtonsoft.Json

Step 3: Create a layout page
Create a layout page in Views-> Shared ->_Layout.cshtml and add reference of angularjs and jquery.


        
        
        
        Student Information
    
    
        @RenderBody()
    

Step 4: Create a view model “Student” in model folder

public class StudentVM
{
   public int RollNo { get; set; }
   public string StudentName { get; set; }
   public string Class { get; set; }
   public string ClassTeacher { get; set; }
}

Step 5: Create StudentsController
Create StudentsController in Controller folder like following. Here GetSerializedStudentVMS method serialized Student model to JSON.

 
public class StudentsController : Controller
    {
        //
        // GET: /Students/

        public ActionResult Index()
        {
            return View("Index", "", GetSerializedStudentVMS());
        }

        public string GetSerializedStudentVMS()
        {
            var students = new[]
             {
                    new StudentVM {RollNo = 1, StudentName = "Jamal Uddin", Class="One", ClassTeacher="Mr. Anowar Hossain"},
                    new StudentVM {RollNo = 5, StudentName = "Kamal Hossain", Class="Two", ClassTeacher="Mr. Shahana Begum"},
                    new StudentVM {RollNo = 10, StudentName = "Jahid Hasan", Class="Three", ClassTeacher="Mr. Lutfor Rahman"},
                };
          
            //Used to make property name as camel case
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

           return JsonConvert.SerializeObject(students, Formatting.None, settings); //Returns students list as JSON
        }

    }

Step 6: Create index view
Right click of index action of StudentsController, click view and a view will automatically create to Views-> Students ->index.cshtml

Change the index.cshtml like following

@model string

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Roll No Student Name Class Course Teacher
{{student.rollNo}} {{student.studentName}} {{student.class}} {{student.classTeacher}}

Here ng-init used to initialize the json object and ng-repeat works like foreach.

Step 7: Change RouteConfig.cs
Change RouteConfig like following to run StudentController by default.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Now run the application. Yes you will see the student information in a table. Thanks for your patient 

A SignalR Application for real time notification using AngularJS and toastr

SignalR is a new developer’s API provided for ASP.NET web applications, used to add “real time” web functionality to ASP.NET applications. “Real Time” web functionality is the ability to have server code to push contents to connected clients.

Uses
1. Notification
2. Chat application
3. Real time monitoring application
4. Job progress update etc.

So, let’s start to create a SignalR Application. In this program I will assign a task for a person and everybody will get notification.

Step 1: Create a ASP.NET MVC application with basic template

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Basic Template and Razor as view engine

Step 2: Install required packages
Install nuget package for SignalR. To install click right button of the project and then click Manages NuGet packages. Search SignalR and then install Microsoft SignalR as follows.

installNuget

Run the following command in package manager console to install packages

PM> Install-Package angularjs
PM> Install-Package toastr

Step 3: Create Startup class

Create a Startup class in project root directory. Create Stratup.cs file and modify as follows.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRApp.Startup))]

namespace SignalRApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Step 4: Create signalR hub

Create a SignalR hub name NotificationHub in root directory and inherit Hub class. Modify the class as follows

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRApp
{
    
    [HubName("notification")]
    public class NotificationHub : Hub
    {
         public void PushNotification(string msg)
         {
             Clients.All.response(msg);
         }
    }
}

Here Clients.All means all user will get notification. It can be configured on the basis of group and individual.

Step 5: Create HomeController and index view

Create a Home controller by right click on controller folder. Create an index view in Views->Hoome->index.cshtml by right clicking in index action of Home controller.

HomeController.cs


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

namespace SignalRApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

    }
}

Index.cshtml


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Please entry a task

Enter a Task:

Here mainController and sendMessage() is declared. I will define it later.

Step 6: Change bundle config

Change BundleConfig and add customScripts, angular, signalr, jquery, toastr buddle as follows.


    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/customScripts").Include(
                      "~/Scripts/Application/app.js",
                      "~/Scripts/Application/mainController.js"));


            bundles.Add(new ScriptBundle("~/bundles/angular").Include(
                       "~/Scripts/angular.js"));

            bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
                       "~/Scripts/jquery.signalR-2.1.2.js"));

                        
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));


            bundles.Add(new ScriptBundle("~/bundles/toastr").Include(
                        "~/Scripts/toastr.js*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            //bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
               //"~/Content/bootstrap.css",
               "~/Content/toastr.css",
               "~/Content/site.css"));


            BundleTable.EnableOptimizations = false;
        }
    }

Here I add app.js and mainController.js in customScripts bundle. I will add it later.
And add bundle reference and ng-app in Views->Shared->_Layout.cshtml

_Layout.cshtml





    
    
    @ViewBag.Title
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")


    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/toastr")
    @Scripts.Render("~/bundles/signalr")
    
    @Scripts.Render("~/bundles/angular")
    @Scripts.Render("~/bundles/customScripts")
    
    @RenderSection("scripts", required: false)



Step 7: Add app.js and mainController.js in Scripts->Application folder

App.js


(function () {
    angular.module('app', []);

    $(function () {
        $.connection.hub.logging = true;
        $.connection.hub.start();
    });


    $.connection.hub.error(function (err) {
        console.log('An error occurred: ' + err);
    });

    angular.module('app')
       .value('notification', $.connection.notification)
       .value('toastr', toastr);

})();

mainController.js

angular.module('app').controller('mainController', function ($scope, notification, toastr) {
    $scope.messages = [];

    $scope.sendMessage = function () {
        var inputval = taskForm.elements.txtTask.value;
        taskForm.elements.txtTask.value = "";
        notification.server.pushNotification(inputval);
        $scope.newMessage = "";
    };

    notification.client.response = function onNewMessage(message) {
        displayMessage(message);
        $scope.$apply();
    };

    function displayMessage(message) {
        toastr.success(message); //To nofiy as fadin and fadout
    }

});

Now run the application and write a text in text box, open two or three browser, you will get same notification like below.

output

Thanks for your patient !

A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine

Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package jQuery
PM> Install-Package angularjs -Version 1.2.26
PM> Install-Package Newtonsoft.Json
PM> Install-Package MvcScaffolding

Step 3: Create Connection String
Create connection string and name DB name as SPADB

  
    
  

Step 4: Create model

Create Trainer model

    public class Trainer
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Venue { get; set; }
    }

Step 5: Create Repository
Create repository for Trainer model. Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.

The overall folder structure looks like following.

st-final

SPAContext.cs

    public class SPAContext : DbContext
    {
        public SPAContext()
            : base("SPAContext")
        {
        }
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges());

        public DbSet Trainers { get; set; }

        public DbSet Trainings { get; set; }
    }

TrainerRepository.cs

    public class TrainerRepository : ITrainerRepository
    {
        SPAContext context = new SPAContext();

        public TrainerRepository()
            : this(new SPAContext())
        {

        }
        public TrainerRepository(SPAContext context)
        {
            this.context = context;
        }


        public IQueryable All
        {
            get { return context.Trainers; }
        }

        public IQueryable AllIncluding(params Expression>[] includeProperties)
        {
            IQueryable query = context.Trainers;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Trainer Find(long id)
        {
            return context.Trainers.Find(id);
        }

        public void InsertOrUpdate(Trainer trainer)
        {
            if (trainer.Id == default(long))
            {
                // New entity
                context.Trainers.Add(trainer);
            }
            else
            {
                // Existing entity
                context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
            }
        }

        public void Delete(long id)
        {
            var trainer = context.Trainers.Find(id);
            context.Trainers.Remove(trainer);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }

    public interface ITrainerRepository : IDisposable
    {
        IQueryable All { get; }
        IQueryable AllIncluding(params Expression>[] includeProperties);
        Trainer Find(long id);
        void InsertOrUpdate(Trainer trainer);
        void Delete(long id);
        void Save();
    }

UnitOfWork.cs

    public class UnitOfWork : IDisposable
    {
        private SPAContext context;
        public UnitOfWork()
        {
            context = new SPAContext();
        }

        public UnitOfWork(SPAContext _context)
        {
            this.context = _context;
        }

        private TrainingRepository _trainingRepository;

        public TrainingRepository TrainingRepository
        {
            get
            {

                if (this._trainingRepository == null)
                {
                    this._trainingRepository = new TrainingRepository(context);
                }
                return _trainingRepository;
            }
        }


        private TrainerRepository _trainerRepository;

        public TrainerRepository TrainerRepository
        {
            get
            {

                if (this._trainerRepository == null)
                {
                    this._trainerRepository = new TrainerRepository(context);
                }
                return _trainerRepository;
            }
        }

        public void Dispose()
        {
            context.Dispose();
            GC.SuppressFinalize(this);
        }
    }

Step 6: Add migration

Run the following command to add migration
PM> Enable-Migrations
PM> Add-Migration initialmigration
PM> Update-Database –Verbose

Step 7: Create API Controllers
Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

TrainersController-2

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.

    public class TrainersController : ApiController
    {
        private UnitOfWork unitOfWork = new UnitOfWork();

        public IEnumerable Get()
        {
            List lstTrainer = new List();
            lstTrainer = unitOfWork.TrainerRepository.All.ToList();
            return lstTrainer;
        }

        //// GET api/trainers/5
        public Trainer Get(int id)
        {
            Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
            return objTrainer;
        }

   
        public HttpResponseMessage Post(Trainer trainer)
        {

            if (ModelState.IsValid)
            {
                unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
                unitOfWork.TrainerRepository.Save();
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }


        private IEnumerable GetErrorMessages()
        {
            return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
        }

   

        // PUT api/trainers/5
        public HttpResponseMessage Put(int Id, Trainer trainer)
        {
            if (ModelState.IsValid)
            {
                unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
                unitOfWork.TrainerRepository.Save();
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }

        // DELETE api/trainers/5
        public HttpResponseMessage Delete(int id)
        {
            Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
            if (objTrainer == null)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            unitOfWork.TrainerRepository.Delete(id);
            unitOfWork.TrainerRepository.Save();

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
    }

Step 9: Create Layout and Home Controller
Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home

Home Controller

    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

    }

_Layout.cshtml



    Training Registration



    @RenderBody()



Index.cshtml


@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Home

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.


var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {

        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });

        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });

        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });

        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });

        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.


'use strict';

//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {

    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },

        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },

        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },

        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },

        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };

});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers

'use strict';

//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});


//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});


//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);

    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates
Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.

All.html

Trainers Details

Name Email Venue Action
{{trainer.name}} {{trainer.email}} {{trainer.venue}} Delete |Edit

Add.html


Trainer Name
Email
Venue
Cancel

Edit.html

Name
Email
Venue

Step 14: Add references to the Layout
Modify the _Layout.cshtml to add references

_Layout.cshtml






    Training Registration

    
    
    
    
    
    
    



    @RenderBody()



Now run you application and add, delete, modify and get all trainer information. Thanks for your patient!

A mini SPA with ASP.NET MVC and AngularJS

SPA stands for Single Page Application; I think you already have little idea on it. Here I will demonstrate a mini SPA with ASP.NET MVC and AngularJS. So, let’s start.

Step 1: Create a ASP.NET MVC application with empty template

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine

Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package jQuery
PM> Install-Package angularjs -Version 1.0.7
PM> Install-Package Newtonsoft.Json

Step 3: Create View model
In this application I will try to demonstrate two pages for Trainer and Training. For this purpose, create TrainerVM, TrainingVM, RegistrationVm view model in Model folder. JSONBuilder is a class in Model folder which make model as json serialized.

    public class TrainingVm
    {
        public string TrainingCode { get; set; }
        public string Title { get; set; }
        public string Trainer { get; set; }
    }



    public class TrainerVm
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Venue { get; set; }
    }



    public class RegistrationVm
    {
        public string Trainings { get; set; }
        public string Trainers { get; set; }
    }




public class JSONBuilder
    {
        public RegistrationVm BuildRegistrationVm()
        {
            var registrationVm = new RegistrationVm
            {
                Trainings = GetSerializedTraining(),
                Trainers = GetSerializedTrainers()
            };

            return registrationVm;
        }

        public string GetSerializedTraining()
        {
            var trainings = new[]
                {
                    new TrainingVm {TrainingCode = "TRA001", Title = "ASP.NET MVC 4", Trainer="Mahedee Hasan"},
                    new TrainingVm {TrainingCode = "TRA002", Title = "ASP.NET Web Form", Trainer="Asrafuzzaman"},
                    new TrainingVm {TrainingCode = "TRA003", Title = "AngularJs Fundamental", Trainer="Foysal Alam"},
                    new TrainingVm {TrainingCode = "TRA004", Title = "ASP.NET MVC 5 with web API", Trainer="Asfaquzzaman"},
                };
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            var serializeCourses = JsonConvert.SerializeObject(trainings, Formatting.None, settings);
            return serializeCourses;
        }


        public string GetSerializedTrainers()
        {
            var trainers = new[]
                {
                    new TrainerVm {Name = "Mahedee Hasan", Email = "mahedee.hasan@gmail.com", Venue="Leadsoft Bangladesh Ltd"},
                    new TrainerVm {Name = "Asrafuzzaman", Email = "asraf@gmail.com", Venue="Leadsoft Bangladesh Ltd"},
                    new TrainerVm {Name = "Foysal Alam", Email = "foysal@gmail.com", Venue="Leadsoft Bangladesh Ltd"},
                    new TrainerVm {Name = "Asfaquzzaman", Email = "asfaq@gmail.com", Venue="Leadsoft Bangladesh Ltd"},
                };
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            var serializedInstructors = JsonConvert.SerializeObject(trainers, Formatting.None, settings);
            return serializedInstructors;
        }
    }

Step 4: Create a RegistrationController in controller folder

 
public class RegistrationController : Controller
    {
        private JSONBuilder jsonBuilder = new JSONBuilder();

        public ActionResult Index()
        {
            return View(jsonBuilder.BuildRegistrationVm());
        }

    }

Step 5: Create TrainingController and TrainerController
Create TrainingsController.js and TrainersController.js in Scripts->Application->Controllers folder

TrainersController.js

'use strict';

registrationModule.controller("TrainersController", function ($scope, registrationData) {
    $scope.trainers = registrationData.trainers;
});

TrainingsController.js

'use strict';

registrationModule.controller("TrainingsController", function ($scope, registrationData) {
    $scope.trainings = registrationData.trainings;
});

I will define registrationModule and registrationData in next steps.

Step 6: Create registrationModule
Create registrationModule.js in Scripts->Application. This is the configuration file for angular routing in client side.

var registrationModule = angular.module("registrationModule", [])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainings', {
            templateUrl: '/templates/Trainings.html',
            controller: 'TrainingsController'
        });

        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers.html',
            controller: 'TrainersController'
        });

        $locationProvider.html5Mode(true);
    });

Here you might see that I map template and controller on corresponding routing. But I didn’t declare template yet. I will declare template in next steps.

Step 7: Create a layout page
Create a layout page in Views-> Shared ->_Layout.cshtml and add reference of angularjs, jquery and registration module.


    
        
        
        

        Training Registration
        @RenderSection("JavascriptInHead", required:false)
    
    
        @RenderBody()
    

Step 8: Create Index view
Right click on Index action of Registration controller and add a view. Modify the view as following.

@model MiniSPA.Models.RegistrationVm

@{
    ViewBag.Title = "Training Regirstration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section JavascriptInHead
{
    
    
    
}

  • Training Registration

Step 9: Create template
Create training.html and trainer.html in templates folder as follows

Trainer.html

 
   

Instructors

Trainer Name Email Venue
{{trainer.name}} {{trainer.email}} {{trainer.venue}}

Training.html

Training Details

Training Code Training Title Trainer Name
{{training.trainingCode}} {{training.title}} {{training.trainer}}

Step 10: Modify RouteConfig.cs
Modify the RouteConfig.cs as follows for routing Registration controller default and catching all other parameter.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
            name: "Mini SPA",
            url: "Registration/{*catchall}",
            defaults: new { controller = "Registration", action = "Index", id = UrlParameter.Optional }
            );


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Registration", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

This structure is not best. So it is not recommended for large application. For large application use service. Hope, I will publish a complete SPA soon. Thanks for your patient!