Ayo Softech

Friday 13 February 2015

count specific character in string Asp.Net

 
You could do this:
int count = test.Split('&').Length - 1;
 
Or with LINQ:
test.Count(x => x == '&');

Wednesday 4 February 2015

What is AngularJS?

AngularJS is a JavaScript framework for organizing HTML code in a more structural, clear and succinct mode. This client-side technology provides easy and light code in order to make developing and even designing as a simple task. AngularJS eliminates most of redundant code specially in CRUD web application. It is a MV(Whatever you like) pattern and not just a MVC.
There are two kinds of accessories which help us to make a bridge between user interface and the core of business and data layer.
Library: These types are set of functions such as JQuery and whenever you use some of them ($.ajax) it will call related function to handle functions.
Frameworks: These types are specific structure for implementation application and developer have to follow these structure. Such as durandal and ember.
AngularJS has different approach to work out our needs, angular embeds new properties inside HTML tags such as “ng-model”, “ng-repeat” which are known as Directives in order to fade our barriers to match and transform data.
On the other hand AngularJS has mingled Ajax and HTML DOM in a good structure which I will describe it more as follow:

Angular Advantages:
  1. It is very good for CRUD web application
  2. It makes testing easy in CRUD web application
  3. You need to write less code
  4. You can run your code more quickly
  5. One of the most popular and famous features in the AngularJS is two way and simple binding
    <input type="text" ng-model="simpleBinding" /><span>{{simpleBinding}}</span>
  1. You do not need to modify HTML DOM
  2. By the aid of directives your tasks are more easy and time saving
  3. By its architecture in MVC or in the better word MVW, decoupling is real and excellent

Monday 2 February 2015

ASP.NET Application Development Using MVC

Overview

ASP.NET provides the MVC framework as an alternate to the ASP.NET Web Forms pattern for developing web applications. MVC (Model-View-Controller) is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features such as Master Pages and Membership-based authentication.

Introduction

The System.Web.Mvc namespace is for ASP.NET MVC. MVC is a standard Design Pattern. MVC has the following components:
  • Controller
  • Classes that handle incoming requests to the application, retrieve model data, and then specify view templates that return a response to the client.
  • Model
  • Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
  • View
  • Template files that your application uses to dynamically generate HTML responses.

Background

In this demonstration, I will design a database using SQL Server Management Studio 2005. I will develop an ASP.NET MVC application and will describe all of its parts.

Let’s Get Started

Open SQL Management Studio 2005. Crate a database and name it Inventory. Design a database table like below:

Figure 1
  1. Open Microsoft Visual Studio 2010
  2. Create a new project (File> New> Project> Visual C#): ASP.NET MVC 3 Web Application
  3. Named it ASPNETMVCApplication
  4. Click on the OK button

Figure 2
  1. Select a template for Internet Application
  2. View engine to Razor
  3. Create a unit test project to uncheck
  4. Click on the OK button

Figure 3
The default project will be created. Now Add Library Package Reference. We will use a .NET Framework data-access technology known as the Entity Framework. The Entity Framework (often referred to as “EF”) supports a development paradigm called code-first. Code-first allows you to create model objects by writing simple classes. You can then have the database created on the fly from your classes, which enables a very clean and rapid development workflow.
We'll start by using the NuGet package manager (automatically installed by ASP.NET MVC 3) to add the EFCodeFirst library to the ASPNETMVCApplication project. This library lets us use the code-first approach. To add Entity Framework reference:
From the Tools menu, select Library Package Manager and then Add Library Package Reference.

Figure 4
In the Add Library Package Reference window, click online.

Figure 5
Click the NuGet Official package source.

Figure 6
Find EFCodeFirst, click on install.

Figure 7
Click on I Accept. Entity Framework will install and will add a reference to the project.

Figure 8
Click on the Close button.

Figure 9

Adding a Model Class

  1. Right click on Models from Solution Explorer
  2. Select Add
  3. Select Class
  4. Name it Book.cs

Figure 10

Figure 11
Add the following properties in the Book.cs file:
namespace ASPNETMVCApplication.Models
{
    public class Book
    {
        public Int64 Id { get; set; }
        public String Title { get; set; }
        public String ISBN { get; set; }
        public Decimal Price { get; set; }
    }
}
Add another class the way you did for Book.cs and name it BookDBContext.cs. Add a System.Data.Entity namespace reference in the BookDBContext.cs file.
using System.Data.Entity;
Add the following code in the BookDBContext class. And derive it from the DbContext class so that all data operations can be handled by the Books property.
Note: The property name Books must be the same as the database table name Books.
Here is the complete code:
using System;
using System.Web;
using System.Data.Entity;

namespace ASPNETMVCApplication.Models
{
    public class BookDBContext:DbContext
    {
        public DbSet<Book> Books { get; set; } 
    }
}
Add a connection string in the web.config file. Remember, the connection string name must be the same as BookDBContext.
<connectionStrings>
    <add name="BookDBContext" 
      connectionString="data source=Home-PC;
                        uid=sa;pwd=1234;Initial Catalog=Inventory" 
      providerName="System.Data.SqlClient" />
</connectionStrings>

Adding the Controller

  1. Right click on Controller from Solution Explorer
  2. Select Add
  3. Select Controller
  4. Name it BookController
  5. Add action methods for Create, Update, Delete, and Details scenarios to Checked

Figure 12

Figure 13
It will add the following code:
namespace ASPNETMVCApplication.Controllers
{
    public class BookController : Controller
    {
        //
        // GET: /Book/

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

        //
        // GET: /Book/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Book/Create

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

        //
        // POST: /Book/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Book/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Book/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Book/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Book/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
Now add the following namespaces in the BookController.cs file:
using System.Linq;
using ASPNETMVCApplication.Models;
Declare a global instance variable of the BookDBContext class in the BookController class.
BookDBContext _db = new BookDBContext();
Add the following code in the Index() method:
public ActionResult Index()
{
   var books = from book in _db.Books
               select book;

   return View(books.ToList());
}
This is the LINQ code for getting books and books.ToList() to display the book list in the View.
Now right click on Solution and select Build to build the solution.

Adding the View

  1. Right click in the Index method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to List
  6. Click on the OK button

Figure 14
It will add the Index.cshtml file.
@model IEnumerable<ASPNETMVCApplication.Models.Book>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            Title
        </th>
        <th>
            ISBN
        </th>
        <th>
            Price
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.ISBN
        </td>
        <td>
            @String.Format("{0:F}", item.Price)
        </td>
    </tr>
}

</table>
Now, add the Create View.

Adding the Create View

  1. Right click on the Create method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Create
  6. Click on the OK button
It will add the Create.cshtml file.
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
  type="text/javascript"></script><script 
  src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
  type="text/javascript"></script>@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Book</legend><div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ISBN)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model =>
Now add the following code in the Create method in the BookController class.
[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        Book book = new Book();
        if (ModelState.IsValid)
        {                   
            book.Title = collection["Title"].ToString();
            book.ISBN = collection["ISBN"].ToString();
            book.Price = Convert.ToDecimal(collection["Price"]);

            _db.Books.Add(book);
            _db.SaveChanges();

            return RedirectToAction("Index");
        }
        else
        {
            return View(book);
        }
    }
    catch
    {
        return View(); 
    }
}
Now we will add the Edit View.

Adding the Edit View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Edit
  6. Click on the OK button

Figure 15
It will add the Edit.cshtml file:
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
  type="text/javascript"></script><script 
  src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
  type="text/javascript"></script>@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Book</legend>@Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ISBN)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model =>
Now add the following code in the Edit method in the BookController class.
public ActionResult Edit(int id)
{
   Book book = _db.Books.Find(id);
   if (book == null)
      return RedirectToAction("Index");

   return View(book);
}

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
   try
   {
       var book = _db.Books.Find(id);

       UpdateModel(book);
       _db.SaveChanges();              
 
        return RedirectToAction("Index");
    }
    catch
    {
        ModelState.AddModelError("", "Edit Failure, see inner exception");
       return View();
    }
}
Now we will add the Details View.

Adding the Details View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Details
  6. Click on the OK button

Figure 16
It will add the Details.cshtml file:
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2><fieldset>
    <legend>Book</legend><div class="display-label">Title</div>
      <div class="display-field">@Model.Title</div>
      <div class="display-label">ISBN</div>
      <div class="display-field">@Model.ISBN</div>
      <div class="display-label">Price</div>
      <div class="display-field">@String.Format("{0:F}", Model.Price)</div>
      </fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>
Add the following code to the Details method of the BookController class.
public ActionResult Details(int id)
{
   Book book = _db.Books.Find(id);

    if (book == null)
      return RedirectToAction("Index");

     return View("Details", book);
}
Now we will add the Delete View.

Adding the Delete View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Delete
  6. Click on the OK button

Figure 17
It will add the Delete.cshtml file.
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2><h3>Are you sure you want to delete this?</h3><fieldset>
    <legend>Book</legend><div class="display-label">Title</div>
    <div class="display-field">@Model.Title</div>
    <div class="display-label">ISBN</div>
    <div class="display-field">@Model.ISBN</div>
    <div class="display-label">Price</div>
    <div class="display-field">@String.Format("{0:F}", Model.Price)</div>
    </fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}
Add the following code to the Delete method in the BookController class.
public ActionResult Delete(int id)
{
    Book book = _db.Books.Find(id);
    if (book == null)
        return RedirectToAction("Index");

    return View(book);
}

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
  Book book = _db.Books.Find(id);
  _db.Books.Remove(book);
  _db.SaveChanges();

  return RedirectToAction("Index");
}
Now run the application. Type /Book in the URL and remember that the port number may be different in your case.

Figure 17
Click Create New Link to add a new book.

Figure 18

Figure 19
This way you can edit, delete, and view details of the books.

Single Page Application (SPA) Web API ,Using AngularJS, and MVC 5


For this you need Visual Studio 2013. You can download Visual Studio 2013 using the following link: Visual Studio Community 2013.

In traditional web applications, the client (browser) initiates the communication with the server by requesting a page. The server then processes the request and sends the HTML of the page to the client. In subsequent interactions with the page, for example the user navigates to a link or submits a form with data, a new request is sent to the server and the flow starts again. The server processes the request and sends a new page to the browser in response to the new action requested by the client.

traditional web applications
Image 1.

In Single-Page Applications (SPAs) the entire page is loaded into the browser after the initial request, but subsequent interactions take place using Ajax requests. This means that the browser must update only the portion of the page that has changed; there is no need to reload the entire page. The SPA approach reduces the time taken by the application to respond to user actions, resulting in a more fluid experience.

Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app.

SAP Lifecycle
Image 2.

Now we will learn this by creating a sample application. In this SPA example I will do CRUD operations on the Student table using the Web API and MVC.

CRUD operation on Student table
Image 3.

The following is my Data Table in design mode:

Data Table in design mode
Image 4.

The script of my Student Table is:
  1. CREATE TABLE [dbo].[Student](  
  2.     [StudentID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [Email] [varchar](500) NULL,  
  5.     [Class] [varchar](50) NULL,  
  6.     [EnrollYear] [varchar](50) NULL,  
  7.     [City] [varchar](50) NULL,  
  8.     [Country] [varchar](50) NULL,  
  9.  CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED   
  10. (  
  11.     [StudentID] ASC  
  12. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  13. ON [PRIMARY]  
  14.   
  15. GO  
  16.   
  17. SET ANSI_PADDING OFF  
  18. GO  
Open Visual Studio 2013 then click New Project.

New Project
Image 5.

Select Web -> ASP.NET Web Application then provide I a name. Then click OK.

Web Application
Image 6.

Select Single Page Application from the template option. Then click OK.

Now right-click on the Models Folder then select Add -> ADO.NET Entity Data Model.

Entity Data Model
Image 7.

manage student
Image 8.

Provide It a name.

designer from database
Image 9.

select data source
Image 10.

save connection string
Image 11.

select table
Image 12.

navigation properties
Image 13.

Now we will add AngularJS references using NuGet. Right-click on Solution Explorer.

AngularJS
 Image 14.

solution Explorer
Image 15.

installing
Image 16.

install package
Image 17.

Now we will add a Web API so right-click on the controller folder then select Add -> Controller.

add controller
Image 18.

web api
Image 19.

controller name
Image 20.

ManageStudentsInfoAPIController.cs is: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using SPA_MVC_StudentApp.Models;  
  12.   
  13. namespace SPA_MVC_StudentApp.Controllers  
  14. {  
  15.     public class ManageStudentsInfoAPIController : ApiController  
  16.     {  
  17.         private SchoolManagementEntities db = new SchoolManagementEntities();  
  18.   
  19.         // GET: api/ManageStudentsInfoAPI  
  20.         public IQueryable<Student> GetStudent()  
  21.         {  
  22.             return db.Student;  
  23.         }  
  24.   
  25.         // GET: api/ManageStudentsInfoAPI/5  
  26.         [ResponseType(typeof(Student))]  
  27.         public IHttpActionResult GetStudent(int id)  
  28.         {  
  29.             Student student = db.Student.Find(id);  
  30.             if (student == null)  
  31.             {  
  32.                 return NotFound();  
  33.             }  
  34.   
  35.             return Ok(student);  
  36.         }  
  37.   
  38.         // PUT: api/ManageStudentsInfoAPI/5  
  39.         [ResponseType(typeof(void))]  
  40.         public IHttpActionResult PutStudent(int id, Student student)  
  41.         {  
  42.             if (!ModelState.IsValid)  
  43.             {  
  44.                 return BadRequest(ModelState);  
  45.             }  
  46.   
  47.             if (id != student.StudentID)  
  48.             {  
  49.                 return BadRequest();  
  50.             }  
  51.   
  52.             db.Entry(student).State = EntityState.Modified;  
  53.   
  54.             try  
  55.             {  
  56.                 db.SaveChanges();  
  57.             }  
  58.             catch (DbUpdateConcurrencyException)  
  59.             {  
  60.                 if (!StudentExists(id))  
  61.                 {  
  62.                     return NotFound();  
  63.                 }  
  64.                 else  
  65.                 {  
  66.                     throw;  
  67.                 }  
  68.             }  
  69.   
  70.             return StatusCode(HttpStatusCode.NoContent);  
  71.         }  
  72.   
  73.         // POST: api/ManageStudentsInfoAPI  
  74.         [ResponseType(typeof(Student))]  
  75.         public IHttpActionResult PostStudent(Student student)  
  76.         {  
  77.             if (!ModelState.IsValid)  
  78.             {  
  79.                 return BadRequest(ModelState);  
  80.             }  
  81.   
  82.             db.Student.Add(student);  
  83.             db.SaveChanges();  
  84.   
  85.             return CreatedAtRoute("DefaultApi"new { id = student.StudentID }, student);  
  86.         }  
  87.   
  88.         // DELETE: api/ManageStudentsInfoAPI/5  
  89.         [ResponseType(typeof(Student))]  
  90.         public IHttpActionResult DeleteStudent(int id)  
  91.         {  
  92.             Student student = db.Student.Find(id);  
  93.             if (student == null)  
  94.             {  
  95.                 return NotFound();  
  96.             }  
  97.   
  98.             db.Student.Remove(student);  
  99.             db.SaveChanges();  
  100.   
  101.             return Ok(student);  
  102.         }  
  103.   
  104.         protected override void Dispose(bool disposing)  
  105.         {  
  106.             if (disposing)  
  107.             {  
  108.                 db.Dispose();  
  109.             }  
  110.             base.Dispose(disposing);  
  111.         }  
  112.   
  113.         private bool StudentExists(int id)  
  114.         {  
  115.             return db.Student.Count(e => e.StudentID == id) > 0;  
  116.         }  
  117.     }  
  118. }  
Now again right-click on the Controller folder then select Add -> Controller.

add another controller
Image 21.

mvc controller
Image 22.

type controller name
Image 23.

After adding ManageStudentInfo Controller we need to add a view.

add view
Image 24.

Index.cshtml
  1. @{  
  2.     ViewBag.Title = "SPA";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  7. <body data-ng-app="ApplicationModule">  
  8.     <div>  
  9.         <div>  
  10.             <div>  
  11.                 <table cellpadding="5" cellspacing="6" width="100%" style="background-color:whitesmoke; border:solid 4px green;">  
  12.                     <tr>  
  13.                         <td style="border: solid 1px gray; width:170px; text-align:center;"><a href="showstudents"> Show All Students </a></td>  
  14.                         <td style="border: solid 1px gray; width:170px; text-align:center;"><a href="addstudent"> Add New Student </a></td>  
  15.                         <td></td>  
  16.                     </tr>  
  17.                 </table>  
  18.             </div>  
  19.             <div>  
  20.                 <div data-ng-view></div>  
  21.             </div>  
  22.         </div>  
  23.     </div>  
  24.   
  25. </body>  
  26.   
  27. @section scripts{  
  28.     <script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>  
  29.     <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script>  
  30.     <script type="text/javascript" src="@Url.Content("~/MyScripts/Module.js")"></script>  
  31.     <script src="~/MyScripts/Services.js"></script>  
  32.     <script type="text/javascript" src="@Url.Content("~/MyScripts/ShowStudentsController.js")"></script>  
  33.     <script type="text/javascript" src="@Url.Content("~/MyScripts/AddStudentController.js")"></script>  
  34.     <script type="text/javascript" src="@Url.Content("~/MyScripts/EditStudentController.js")"></script>  
  35.     <script type="text/javascript" src="@Url.Content("~/MyScripts/DeleteStudentController.js")"></script>  
  36. }  
Note: I will add all these scripts in the following.

Here in this example we will perform the following operations: 
  • ShowAllStudent
  • AddStudent
  • EditStudent
  • DeleteStudent
So we will add a partial view for all these. So right-click on Views then select the ManageStudentInfo folder. Like the following.

manage stdio info
Image 25.

ShowAllStudent.cshtml
  1. <table><tr><td height="10px"></td></tr></table>  
  2. <table cellpadding="4" cellspacing="4" width="90%" align="center"   
  3.        style="background-color: skyblue; border:solid 2px red; padding-top:20px;">  
  4.     <thead>  
  5.         <tr style="background-color:#F5F5F5;">  
  6.             <th>Student ID</th>  
  7.             <th>Name</th>  
  8.             <th>Email</th>  
  9.             <th>Class</th>  
  10.             <th>Enroll Year</th>  
  11.             <th>City</th>  
  12.             <th>Country</th>  
  13.             <th></th>  
  14.             <th></th>  
  15.         </tr>  
  16.     </thead>  
  17.     <tbody>  
  18.         <tr data-ng-repeat="Stud in Students">  
  19.             <td>{{Stud.studentID}}</td>  
  20.             <td>{{Stud.name}}</td>  
  21.             <td>{{Stud.email}}</td>  
  22.             <td>{{Stud.class}}</td>  
  23.             <td>{{Stud.enrollYear}}</td>  
  24.             <td>{{Stud.city}}</td>  
  25.             <td>{{Stud.country}}</td>  
  26.             <td><a ng-click="editStudent(Stud.studentID)">Edit</a></td>  
  27.             <td><a ng-click="deleteStudent(Stud.studentID)">Delete</a></td>  
  28.         </tr>  
  29.     </tbody>  
  30. </table>  
Add the same for AddStudent, EditStudent, DeleteStudent partial view. And use the following code.

AddStudent.cshtml
  1. @{  
  2.     ViewBag.Title = "Add New Student";  
  3. }  
  4. <table><tr><td height="10px"></td></tr></table>  
  5.   
  6. <table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color: skyblue;   
  7. border:solid 2px red; padding-top:20px;">  
  8.     <tr><td colspan="3" style="background-color:gray; font-size:18pt;   
  9. font-weight:bold; height:30px; text-align:center;">Add New Student</td></tr>  
  10.     <tr>  
  11.         <td style="text-align:right;">Student ID</td>  
  12.         <td><input type="text" ng-model="StudentID" />  </td>  
  13.     </tr>  
  14.     <tr>  
  15.         <td style="text-align:right;">Name</td>  
  16.         <td><input type="text" ng-model="Name" />  </td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td style="text-align:right;">Email</td>  
  20.         <td><input type="text" ng-model="Email" />  </td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td style="text-align:right;">Class</td>  
  24.         <td><input type="text" ng-model="Class" />  </td>  
  25.     </tr>  
  26.     <tr>  
  27.         <td style="text-align:right;">Enroll Year</td>  
  28.         <td><input type="text" ng-model="EnrollYear" />  </td>  
  29.     </tr>  
  30.     <tr>  
  31.         <td style="text-align:right;">City</td>  
  32.         <td><input type="text" ng-model="City" />  </td>  
  33.     </tr>  
  34.     <tr>  
  35.         <td style="text-align:right;">Country</td>  
  36.         <td><input type="text" ng-model="Country" />  </td>  
  37.     </tr>  
  38.     <tr>  
  39.         <td></td>  
  40.         <td>  
  41.             <input type="button" value="Save" data-ng-click="save()" />  
  42.         </td>  
  43.     </tr>  
  44.   
  45. </table>  
DeleteStudent.cshtml
  1. @{  
  2.     ViewBag.Title = "Delete Student";  
  3. }  
  4.   
  5. <table><tr><td height="10px"></td></tr></table>  
  6.   
  7. <table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color: skyblue; border:solid 2px red; padding-top:20px;">  
  8.     <tr><td colspan="3" style="background-color:gray; font-size:18pt; font-weight:bold; height:30px; text-align:center;">Delete Student Information</td></tr>  
  9.     <tr>  
  10.   
  11.         <td style="text-align:right;">Student ID</td>  
  12.         <td>{{Student.studentID}}  </td>  
  13.     </tr>  
  14.     <tr>  
  15.   
  16.         <td style="text-align:right;">Name # </td>  
  17.         <td> {{Student.name}}  </td>  
  18.     </tr>  
  19.     <tr>  
  20.         <td style="text-align:right;">Email # </td>  
  21.         <td>{{Student.email}}  </td>  
  22.     </tr>  
  23.     <tr>  
  24.         <td style="text-align:right;">Class # </td>  
  25.         <td>{{Student.class}}  </td>  
  26.     </tr>  
  27.     <tr>  
  28.         <td style="text-align:right;">Enroll Year # </td>  
  29.         <td>{{Student.enrollYear}}  </td>  
  30.     </tr>  
  31.     <tr>  
  32.         <td style="text-align:right;">City # </td>  
  33.         <td>{{Student.city}}  </td>  
  34.     </tr>  
  35.     <tr>  
  36.         <td style="text-align:right;">Country # </td>  
  37.         <td>{{Student.country}}  </td>  
  38.     </tr>  
  39.     <tr>  
  40.         <td></td>  
  41.         <td>  
  42.             <input type="button" value="Delete" ng-click="delete()" />  
  43.         </td>  
  44.     </tr>  
  45.   
  46. </table>  
EditStudent.cshtml
  1. @{  
  2.     ViewBag.Title = "Edit Student";  
  3. }  
  4. <table><tr><td height="10px"></td></tr></table>  
  5.   
  6. <table cellpadding="4" cellspacing="4" width="70%" align="center" style="background-color: skyblue; border:solid 2px red; padding-top:20px;">  
  7.     <tr><td colspan="3" style="background-color:gray; font-size:18pt; font-weight:bold; height:30px; text-align:center;">Edit Student Information</td></tr>  
  8.     <tr>  
  9.   
  10.         <td style="text-align:right;">Student ID</td>  
  11.         <td><input type="text" ng-model="Student.studentID" />  </td>  
  12.     </tr>  
  13.     <tr>  
  14.   
  15.         <td style="text-align:right;">Name</td>  
  16.         <td><input type="text" ng-model="Student.name" />  </td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td style="text-align:right;">Email</td>  
  20.         <td><input type="text" ng-model="Student.email" />  </td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td style="text-align:right;">Class</td>  
  24.         <td><input type="text" ng-model="Student.class" />  </td>  
  25.     </tr>  
  26.     <tr>  
  27.         <td style="text-align:right;">Enroll Year</td>  
  28.         <td><input type="text" ng-model="Student.enrollYear" />  </td>  
  29.     </tr>  
  30.     <tr>  
  31.         <td style="text-align:right;">City</td>  
  32.         <td><input type="text" ng-model="Student.city" />  </td>  
  33.     </tr>  
  34.     <tr>  
  35.         <td style="text-align:right;">Country</td>  
  36.         <td><input type="text" ng-model="Student.country" />  </td>  
  37.     </tr>  
  38.     <tr>  
  39.         <td></td>  
  40.         <td>  
  41.             <input type="button" value="Save" ng-click="save()" />  
  42.             <br />  
  43.             <div>{{error}}</div>  
  44.         </td>  
  45.     </tr>  
  46.   
  47. </table>  
Now, open ManageStudentInfoController.cs and provide the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace SPA_MVC_StudentApp.Controllers  
  8. {  
  9.     public class ManageStudentInfoController : Controller  
  10.     {  
  11.         // GET: ManageStudentInfo  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.         public ActionResult AddNewStudent()  
  17.         {  
  18.             return PartialView("AddStudent");  
  19.         }  
  20.   
  21.         public ActionResult ShowStudents()  
  22.         {  
  23.             return PartialView("ShowAllStudent");  
  24.         }  
  25.   
  26.         public ActionResult EditStudent()  
  27.         {  
  28.             return PartialView("EditStudent");  
  29.         }  
  30.   
  31.         public ActionResult DeleteStudent()  
  32.         {  
  33.             return PartialView("DeleteStudent");  
  34.         }  
  35.     }  
  36. }  
Now add a new folder, MyScripts, to your solution.

And add the following JavaScript files. 
  • Module.js
  • Services.js
  • ShowStudentsController.js
  • AddStudentController.js
  • EditStudentController.js
  • DeleteStudentController.js
Now provide the following code in every JavaScript file.

Module.js
  1. var app = angular.module("ApplicationModule", ["ngRoute"]);  
  2.   
  3. app.factory("ShareData"function () {  
  4.     return { value: 0 }  
  5. });  
  6.   
  7. //Showing Routing  
  8. app.config(['$routeProvider''$locationProvider'function ($routeProvider, $locationProvider) {  
  9.     debugger;  
  10.     $routeProvider.when('/showstudents',  
  11.                         {  
  12.                             templateUrl: 'ManageStudentInfo/ShowStudents',  
  13.                             controller: 'ShowStudentsController'  
  14.                         });  
  15.     $routeProvider.when('/addstudent',  
  16.                         {  
  17.                             templateUrl: 'ManageStudentInfo/AddNewStudent',  
  18.                             controller: 'AddStudentController'  
  19.                         });  
  20.     $routeProvider.when("/editStudent",  
  21.                         {  
  22.                             templateUrl: 'ManageStudentInfo/EditStudent',  
  23.                             controller: 'EditStudentController'  
  24.                         });  
  25.     $routeProvider.when('/deleteStudent',  
  26.                         {  
  27.                             templateUrl: 'ManageStudentInfo/DeleteStudent',  
  28.                             controller: 'DeleteStudentController'  
  29.                         });  
  30.     $routeProvider.otherwise(  
  31.                         {  
  32.                             redirectTo: '/'  
  33.                         });  
  34.       
  35.     $locationProvider.html5Mode(true).hashPrefix('!')  
  36. }]);  
Services.js
  1. app.service("SPACRUDService"function ($http) {  
  2.   
  3.     //Read all Students  
  4.     this.getStudents = function () {  
  5.         
  6.         return $http.get("/api/ManageStudentInfoAPI");  
  7.     };  
  8.   
  9.     //Fundction to Read Student by Student ID  
  10.     this.getStudent = function (id) {  
  11.         return $http.get("/api/ManageStudentInfoAPI/" + id);  
  12.     };  
  13.   
  14.     //Function to create new Student  
  15.     this.post = function (Student) {  
  16.         var request = $http({  
  17.             method: "post",  
  18.             url: "/api/ManageStudentInfoAPI",  
  19.             data: Student  
  20.         });  
  21.         return request;  
  22.     };  
  23.   
  24.     //Edit Student By ID   
  25.     this.put = function (id, Student) {  
  26.         var request = $http({  
  27.             method: "put",  
  28.             url: "/api/ManageStudentInfoAPI/" + id,  
  29.             data: Student  
  30.         });  
  31.         return request;  
  32.     };  
  33.   
  34.     //Delete Student By Student ID  
  35.     this.delete = function (id) {  
  36.         var request = $http({  
  37.             method: "delete",  
  38.             url: "/api/ManageStudentInfoAPI/" + id  
  39.         });  
  40.         return request;  
  41.     };  
  42. });  
ShowStudentsController.js
  1. app.controller('ShowStudentsController'function ($scope, $location, SPACRUDService, ShareData) {  
  2.     loadAllStudentsRecords();  
  3.   
  4.     function loadAllStudentsRecords()  
  5.     {  
  6.         var promiseGetStudent = SPACRUDService.getStudents();  
  7.           
  8.         promiseGetStudent.then(function (pl) { $scope.Students = pl.data },  
  9.               function (errorPl) {  
  10.                   $scope.error =  errorPl;  
  11.               });  
  12.     }  
  13.   
  14.     //To Edit Student Information  
  15.     $scope.editStudent = function (StudentID) {  
  16.         ShareData.value = StudentID;  
  17.         $location.path("/editStudent");  
  18.     }  
  19.   
  20.     //To Delete a Student  
  21.     $scope.deleteStudent = function (StudentID) {  
  22.         ShareData.value = StudentID;  
  23.         $location.path("/deleteStudent");  
  24.     }  
  25. });  
AddStudentController.js
  1. app.controller('AddStudentController'function ($scope, SPACRUDService) {  
  2.     $scope.StudentID = 0;  
  3.        
  4.     $scope.save = function () {  
  5.         var Student = {  
  6.             StudentID: $scope.StudentID,  
  7.             Name: $scope.Name,  
  8.             Email: $scope.Email,  
  9.             Class: $scope.Class,  
  10.             EnrollYear: $scope.EnrollYear,  
  11.             City: $scope.City,  
  12.             Country: $scope.Country  
  13.         };  
  14.   
  15.         var promisePost = SPACRUDService.post(Student);  
  16.   
  17.         promisePost.then(function (pl) {  
  18.             alert("Student Saved Successfully.");  
  19.         },  
  20.               function (errorPl) {  
  21.                   $scope.error = 'failure loading Student', errorPl;  
  22.               });  
  23.   
  24.     };  
  25.   
  26. });  
EditStudentController.js
  1. app.controller("EditStudentController"function ($scope, $location, ShareData, SPACRUDService) {  
  2.     getStudent();  
  3.   
  4.     function getStudent() {          
  5.         var promiseGetStudent = SPACRUDService.getStudent(ShareData.value);  
  6.   
  7.         promiseGetStudent.then(function (pl)  
  8.         {  
  9.             $scope.Student = pl.data;  
  10.         },  
  11.               function (errorPl) {  
  12.                   $scope.error = 'failure loading Student', errorPl;  
  13.               });  
  14.     }  
  15.   
  16.     $scope.save = function () {  
  17.         var Student = {  
  18.             StudentID: $scope.Student.studentID,  
  19.             Name: $scope.Student.name,  
  20.             Email: $scope.Student.email,  
  21.             Class: $scope.Student.class,  
  22.             EnrollYear: $scope.Student.enrollYear,  
  23.             City: $scope.Student.city,  
  24.             Country: $scope.Student.country  
  25.         };   
  26.   
  27.         var promisePutStudent = SPACRUDService.put($scope.Student.studentID, Student);  
  28.         promisePutStudent.then(function (pl)  
  29.         {  
  30.             $location.path("/showstudents");  
  31.         },  
  32.               function (errorPl) {  
  33.                   $scope.error = 'failure loading Student', errorPl;  
  34.               });  
  35.     };  
  36.   
  37. });  
DeleteStudentController.js
  1. app.controller("DeleteStudentController"function ($scope, $location, ShareData, SPACRUDService) {  
  2.   
  3.     getStudent();  
  4.     function getStudent() {  
  5.   
  6.         var promiseGetStudent = SPACRUDService.getStudent(ShareData.value);  
  7.   
  8.   
  9.         promiseGetStudent.then(function (pl) {  
  10.             $scope.Student = pl.data;  
  11.         },  
  12.               function (errorPl) {  
  13.                   $scope.error = 'failure loading Student', errorPl;  
  14.               });  
  15.     }  
  16.   
  17.     $scope.delete = function () {  
  18.         var promiseDeleteStudent = SPACRUDService.delete(ShareData.value);  
  19.   
  20.         promiseDeleteStudent.then(function (pl) {  
  21.             $location.path("/showstudents");  
  22.         },  
  23.               function (errorPl) {  
  24.                   $scope.error = 'failure loading Student', errorPl;  
  25.               });  
  26.     };  
  27.   
  28. });  
Now run the application:

Run the application
Image 26.

Now click on Show All Students.

single page application
Image 27.

Now click on Add New Student.

Add New Student
Image 28.

manage student information
Image 29.

Now click on Edit.

edit student info
Image 30.

delete student information
Image 31.