Skip to main content

AngularJS - Tables

Table data is normally repeatable by nature. ng-repeat directive can be used to draw table easily.  Following example states the use of ng-repeat directive to draw a table. <table> <tr> <th> Name </th> <th> Marks </th> </tr> <tr ng-repeat = "subject in student.subjects" > <td> {{ subject.name }} </td> <td> {{ subject.marks }} </td> </tr> </table> Table can be styled using CSS Styling. <style> table , th , td { border : 1px solid grey ; border - collapse : collapse ; padding : 5px ; } table tr : nth - child ( odd ) { background - color : #f2f2f2; } table tr : nth - child ( even ) { background - color : #ffffff; } </style> Example Following example will showcase all the above mentioned directive. <html> <head> <

A Simple CRUD Operation in AngularJS using Ajax and Asp.Net Web API MVC 4

Create a Table in SQL Server


CREATE TABLE [dbo].[Books](
    [BookID] [int] IDENTITY(1,1) NOT NULL,
    [BookName] [varchar](50) NULL,
    [Category] [varchar](50) NULL,
    [Price] [numeric](18, 2) NULL
    PRIMARY KEY CLUSTERED ( [BookID] ASC )
) ON [PRIMARY]



The Web API

I am using Asp.Net MVC 4 to create my Web API that is the Models and Controllers. I’ll create a Books model, along with a controller.

Model “Books.cs”

using System;

namespace BooksApp.Models
{
    public class Books
    {
        public int BookID { get; set; }
        public string BookName { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
        public string Operation { get; set; }
    }
}


Model “Books.vb”


Imports System.Web

Namespace BooksApp.Models
    Public Class Books
        Public Property BookID() As Integer
            Get
                Return m_BookID
            End Get
            Set(value As Integer)
                m_BookID = value
            End Set
        End Property
        Private m_BookID As Integer

        Public Property BookName() As String
            Get
                Return m_BookName
            End Get
            Set(value As String)
                m_BookName = value
            End Set
        End Property
        Private m_BookName As String

        Public Property Category() As String
            Get
                Return m_Category
            End Get
            Set(value As String)
                m_Category = value
            End Set
        End Property
        Private m_Category As String

        Public Property Price() As Decimal
            Get
                Return m_Price
            End Get
            Set(value As Decimal)
                m_Price = value
            End Set
        End Property
        Private m_Price As Decimal

        Public Property Operation() As String
            Get
                Return m_Ops
            End Get
            Set(value As String)
                m_Ops = value
            End Set
        End Property
        Private m_Ops As String
    End Class
End Namespace


After you have successfully created the model in Web API MVC 4, now create the controller.

Note: If you are new to Web API, then I would suggest you to click the below link to learn the basic procedure of creating a Web API from scratch.


Controller “BooksController.cs”



using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using BooksApp.Models;
using System.Data.SqlClient;

namespace BooksApp.Controllers
{
    public class BooksController : ApiController
    {
        const string sConnString = "Data Source=DNA;Persist Security Info=False;" +
            "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;";

        // LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS.
        List<Books> MyBooks = new List<Books>();

        [HttpPost()]
        public IEnumerable<Books> Perform_CRUD(Books list) 
        {
            bool bDone = false;

            using (SqlConnection con = new SqlConnection(sConnString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT *FROM dbo.Books"))
                {
                    cmd.Connection = con;
                    con.Open();

                    switch (list.Operation)
                    {
                        case "SAVE":
                            if (list.BookName != "" & list.Category != "" & list.Price > 0)
                            {
                                cmd.CommandText = "INSERT INTO dbo.Books (BookName, Category, Price) " +
                                    "VALUES (@BookName, @Category, @Price)";

                                cmd.Parameters.AddWithValue("@BookName", list.BookName.Trim());
                                cmd.Parameters.AddWithValue("@Category", list.Category.Trim());
                                cmd.Parameters.AddWithValue("@Price", list.Price);

                                bDone = true;
                            }
                            break;

                        case "UPDATE":
                            if (list.BookName != "" & list.Category != "" & list.Price > 0)
                            {
                                cmd.CommandText = "UPDATE dbo.Books SET BookName = @BookName, Category = @Category, " + 
                                    "Price = @Price WHERE BookID = @BookID";

                                cmd.Parameters.AddWithValue("@BookName", list.BookName.Trim());
                                cmd.Parameters.AddWithValue("@Category", list.Category.Trim());
                                cmd.Parameters.AddWithValue("@Price", list.Price);
                                cmd.Parameters.AddWithValue("@BookID", list.BookID);

                                bDone = true;
                            }
                            break;

                        case "DELETE":
                            cmd.CommandText = "DELETE FROM dbo.Books WHERE BookID = @BookID";
                            cmd.Parameters.AddWithValue("@BookID", list.BookID);

                            bDone = true;
                            break;
                    }

                    if (bDone)
                    {
                        cmd.ExecuteNonQuery();
                    }

                    con.Close();
                }
            }

            if (bDone)
            {
                GetData();
            }
            return MyBooks;
        }

        private void GetData()
        {
            using (SqlConnection con = new SqlConnection(sConnString))
            {
                SqlCommand objComm = new SqlCommand("SELECT *FROM dbo.Books ORDER BY BookID DESC", con);
                con.Open();

                SqlDataReader reader = objComm.ExecuteReader();

                // POPULATE THE LIST WITH DATA.
                while (reader.Read())
                {
                    MyBooks.Add(new Books
                    {
                        BookID = Convert.ToInt32(reader["BookID"]),
                        BookName = reader["BookName"].ToString(),
                        Category = reader["Category"].ToString(),
                        Price = Convert.ToDecimal(reader["Price"])
                    });
                }

                con.Close();
            }
        }
    }


Controller “BooksController.vb” (For Visual Basic)



Option Explicit On

Imports System.Net.Http
Imports System.Web.Http

Imports System.Data.SqlClient
Imports BooksApp.BooksApp.Models

Namespace BooksApp
    Public Class BooksController
        Inherits ApiController

        Const sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _
            "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;"

        ' LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS.
        Dim MyBooks As New List(Of Books)()

        <HttpPost()> _
        Public Function Perform_CRUD(list As Books) As IEnumerable(Of Books)

            Dim bDone As Boolean = False

            Using con As SqlConnection = New SqlConnection(sConnString)
                Using cmd As SqlCommand = New SqlCommand("SELECT *FROM dbo.Books")
                    With cmd
                        .Connection = con
                        con.Open()

                        Select Case list.Operation
                            Case "SAVE"
                                If Trim(list.BookName) <> "" And Trim(list.Category) <> "" And
                                    Val(list.Price) > 0 Then

                                    .CommandText = "INSERT INTO dbo.Books (BookName, Category, Price) " & _
                                        "VALUES (@BookName, @Category, @Price)"

                                    .Parameters.AddWithValue("@BookName", Trim(list.BookName))
                                    .Parameters.AddWithValue("@Category", Trim(list.Category))
                                    .Parameters.AddWithValue("@Price", list.Price)

                                    bDone = True
                                End If

                            Case "UPDATE"
                                If Trim(list.BookName) <> "" And Trim(list.Category) <> "" And
                                    Val(list.Price) > 0 Then

                                    .CommandText = "UPDATE dbo.Books SET BookName = @BookName, Category = @Category, " & _
                                        "Price = @Price WHERE BookID = @BookID"

                                    .Parameters.AddWithValue("@BookName", Trim(list.BookName))
                                    .Parameters.AddWithValue("@Category", Trim(list.Category))
                                    .Parameters.AddWithValue("@Price", Val(list.Price))
                                    .Parameters.AddWithValue("@BookID", Val(list.BookID))

                                    bDone = True
                                End If

                            Case "DELETE"
                                .CommandText = "DELETE FROM dbo.Books WHERE BookID = @BookID"
                                .Parameters.AddWithValue("@BookID", Val(list.BookID))

                                bDone = True
                        End Select

                        If bDone Then
                            .ExecuteNonQuery()
                        End If

                        con.Close()
                    End With
                End Using
            End Using

            If bDone Then
                GetData()
                Return MyBooks
            End If
        End Function

        Private Sub GetData()
            Using con As SqlConnection = New SqlConnection(sConnString)
                Dim objComm As New SqlCommand("SELECT *FROM dbo.Books ORDER BY BookID DESC", con)
                con.Open()

                Dim reader As SqlDataReader = objComm.ExecuteReader()

                ' POPULATE THE LIST WITH DATA.
                While reader.Read()
                    MyBooks.Add(New Books() With { _
                        .BookID = CInt(reader("BookID")), _
                        .BookName = reader("BookName").ToString(), _
                        .Category = reader("Category").ToString(), _
                        .Price = CDbl(reader("Price")) _
                     })
                End While

                con.Close()
            End Using
        End Sub
    End Class
End Namespace

We are now done with our backend. Let’s now create a small AngularJS front end Application.


The CSS and CDN’s


<!DOCTYPE html>
<html>
<head>
    <title>CRUD Operation in AngularJS</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        div {
            width:600px;
            text-align:center;
        }
        ul {
            list-style:none;
            margin:5px; padding:0;
            display:inline-block;
        }
        li {
            border:none;
            background:#FFF;
        }
        input, select {
            font:13px Verdana;
            width:170px;
            padding:3px;
        }
        button {
            margin:5px;
        }
        table, th, td {
            font:13px Verdana;
            border:solid 1px #CCC;
            width:600px;
        }
        th {font-weight:bold;}
    </style>
</head>


The Body (Model)


<body>
    <div ng-app="myApp" 
        ng-controller="myController"
        ng-init="myList=[
            { category:'Business' },
            { category:'Computers' },
            { category:'Programming' },
            { category:'Science' }]">

        <div>
            <!--BASIC FORM CONTROLS-->
            <label>{{bookid}}</label>
            <ul>
                <li><input name="bookname" type="text" 
                    ng-model="bookname" 
                        placeholder="Enter the Book Name" /></li>
            </ul>
            <ul>
                <li>
                    <select name="category" ng-model="category" 
                        ng-options="c.category as c.category for c in myList">
                        <option value="">-- Select a Category --</option>
                    </select>
                </li>
            </ul>
            <ul>
                <li><input name="price" type="number" 
                    ng-model="price" placeholder="Enter the Price" /></li>
            </ul>
 
            <!--TWO BUTTON CONTROLS-->
            <p>
                <button id="save" ng-disabled="isDisabled" ng-click="save()">Save My Book</button>
                <button id="update" ng-click="update()">Update My Book</button>
            </p>

            <hr />

            <table>
                <tr>
                    <th>ID</th>
                    <th>Book Name</th>
                    <th>Category</th>
                    <th>Price</th>
                </tr>
                <tr ng-repeat="myBooks in arrBooks" ng-click="edit(myBooks)">
                    <td>{{ myBooks.BookID }}</td>
                    <td>{{ myBooks.BookName }}</td>
                    <td>{{ myBooks.Category }}</td>
                    <td>{{ myBooks.Price }}</td>

                    <td><button id="delete" ng-click="del(myBooks)">Delete</button></td>
                </tr>
            </table>
        </div>
    </div>
</body>



The Controller (Script)


<script>
    var myApp = angular.module('myApp', []);

    myApp.controller('myController',
        function ($scope, $http) {

            $scope.save = function () {
                Perform_CRUD('SAVE', 0)
                ClearInput();
            };

            $scope.edit = function (myBook) {
                $scope.bookid = myBook.BookID;
                $scope.bookname = myBook.BookName;
                $scope.category = myBook.Category;
                $scope.price = myBook.Price;

                $scope.isDisabled = true;
            };

            $scope.update = function () {
                Perform_CRUD('UPDATE', $scope.bookid);
                $scope.isDisabled = false;

                ClearInput();
            };

            $scope.del = function (myBook) {
                Perform_CRUD('DELETE', myBook.BookID)
            };

            function Perform_CRUD(ops, id) {
                var request = {
                    method: 'post',
                    url: '/api/books/',
                    data: {
                        BookID: id,
                        BookName: $scope.bookname,
                        Category: $scope.category,
                        Price: $scope.price,
                        Operation: ops
                    },
                    dataType: 'json',
                    contentType: "application/json"
                };

                // POST DATA WITH $http.
                $http(request)
                    .success(function (data) {

                        var i = 0;      // JUST A COUNTER.
                        $scope.arrBooks = new Array;

                        // LOOP THROUGH EACH DATA.
                        $.map(data, function () {
                            var b = {
                                BookID: data[i].BookID,
                                BookName: data[i].BookName,
                                Category: data[i].Category,
                                Price: data[i].Price
                            };

                            $scope.arrBooks.push(b);    // ADD DATA TO THE ARRAY.
                            i += 1;
                        });
                    })
                    .error(function () {

                    });
            };

            // CLEAR ALL INPUT FIELDS AFTER EVERY OPERATION.
            function ClearInput() {
                $scope.bookid = '';
                $scope.bookname = '';
                $scope.category = '';
                $scope.price = '';
            }
        });
</script>
</html>


I am posting the data using AngularJS $http service. The data is serialized using JSON and posted to the Web API controller. The method I have used is post and I have mentioned thedataType. Once, the API receives and processes the data successfully it will return the entire table’s row to display.

I also have four $scope functions inside my controller that will perform insert (or save), edit, update and delete functions. Each method will extract methods for an operation and call the Perform_CRUD() function, which will POST the data to the API.

That’s it. If you find this example (demo) useful, then please share it with your friends on social media platforms etc. In-addition, if you have any queries related to this article and example, leave a message below.

Thanks for reading.

Comments

Popular posts from this blog

AngularJS - Tables

Table data is normally repeatable by nature. ng-repeat directive can be used to draw table easily.  Following example states the use of ng-repeat directive to draw a table. <table> <tr> <th> Name </th> <th> Marks </th> </tr> <tr ng-repeat = "subject in student.subjects" > <td> {{ subject.name }} </td> <td> {{ subject.marks }} </td> </tr> </table> Table can be styled using CSS Styling. <style> table , th , td { border : 1px solid grey ; border - collapse : collapse ; padding : 5px ; } table tr : nth - child ( odd ) { background - color : #f2f2f2; } table tr : nth - child ( even ) { background - color : #ffffff; } </style> Example Following example will showcase all the above mentioned directive. <html> <head> <

How to Password Protect a Directory on Your Website

Password protecting a directory on your site is actually fairly easy. Webmasters typically want to protect a directory if they have information that they want to make available only to a selected number of people. This guide teaches how you can make a folder on  your website  accessible only to people with the appropriate password. If Your Web Host Has a Control Panel Before you dive into the task of manually password-protecting a directory using Apache's built-in facilities, you might want to check out your web host's control panel to see if they already provide the facility for protecting directories. In my experience, many commercial web hosts already provide an easy way for you to password-protect your directories. If such facility is already available, it's probably best to use it since it will save you time, particularly if you are not familiar with shell command lines and editing of .htaccess files. Otherwise, read on. System Requirements You wi

AMP Vs Responsive Web Design-Speed Vs Flexibility

WHAT IS RESPONSIVE WEB DESIGN? Responsive web design can be achieved using CSS3 media queries. Media queries allow web pages to use different CSS styles based on a user’s browser width. So according to mobile device width, one can easily write logical CSS media queries to make them compatible with different mobile devices. Regarding AMP Vs Responsive Web Design, Responsive Web Design focused on flexibility. Moreover, we can’t forget Google to get most of the business via a search engine. Now a day, Google is the topmost search engine. Google gives a lot of importance to page speed of website to improve the user experience. The majority of people are still using websites on mobile devices as opposed to mobile applications. Obviously, there is a specific audience who uses iOS apps and Android apps for eCommerce portals and others. Google introduce mobile-friendly feature when they show a result for any search term. So whenever your website list in Google searches result, you can se