Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

ASP.NET MVC Hotel Booking System Using AngularJS

4.83/5 (28 votes)
27 Oct 2016CPOL7 min read 73.7K   4.4K  
Tutorial for creating a simple web based Hotel Room Booking System using MVC, AngularJS, and WebAPI
In this article, we will learn how to create a simple web based Hotel Room Booking System using MVC, AngularJS, and WebAPI.

Image 1

Introduction

In this article, we will learn how to create a simple web based Hotel Room Booking System using MVC, AngularJs and WEB API.

What is SHANU Hotel Room Booking?

SHANU Hotel Room Booking is a web based simple Hotel Room Booking System. User can add their hotel room details and block rooms for booked dates. SHANU Hotel Booking has two modules:

  1. Dashboard
  2. Room/Booking CRUD (Add Rooms and Booking)

This application has two modules:

  1. Room Status (Dashboard)
  2. Room/Booking CRUD (Add Room and Manage Bookings)

Room Status

This is the main dashboard module. User can view all the Free/Occupied and Reserved Room Information on dashboard page. This module will help users to view easily the Available free room. The Available free rooms will be in green color and occupied rooms will be in red color and reserved rooms will be in yellow color. This color difference will be useful for users to see which rooms are free, occupied and reserved.

Image 2

In this dashboard page along with Room No and Status, we can also see the details like Payment Status as Paid or Not Paid, Advance amount paid, Total Amount Paid and Booked From and TO date.

Room/Booking CRUD (Add Room and Manage Bookings)

Image 3

In this module, we will manage Room and Room Booking information.

Room Details

Image 4

Here, user can add Room details with Room No, Room Type and Room Price details.

Room/Booking CRUD

Image 5

This is our main part where user will be booking rooms for the visitors. Here, we select Room No, Booking From and TO date, Booking Status as Free, Occupied and Reserved, Payment Type as Paid, Not Paid and Advance Paid, Advance amount paid and Total amount paid. We can also edit and delete the booking details.

Prerequisites

Using the Code

Create Database and Table

The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.

SQL
-- =============================================                                  
-- Author      : Shanu                                    
-- Create date : 2016-10-20                                 
-- Description : To Create Database                            
                               
-- =============================================    
--Script to create DB,Table and sample Insert data    
USE MASTER;    
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB    
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'HotelDB' )    
BEGIN    
ALTER DATABASE HotelDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE    
DROP DATABASE HotelDB ;    
END       
    
CREATE DATABASE HotelDB    
GO    
    
USE HotelDB    
GO    

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'HotelMaster' )    
DROP TABLE HotelMaster    
GO    
    
CREATE TABLE HotelMaster    
(    
  RoomID int identity(1,1),  
   RoomNo VARCHAR(100)  NOT NULL ,  
   RoomType VARCHAR(100)  NOT NULL ,
   Prize    VARCHAR(100)  NOT NULL 
CONSTRAINT [PK_HotelMaster] PRIMARY KEY CLUSTERED          
(         
  RoomID ASC    
   
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]         
) ON [PRIMARY]       

 Insert into HotelMaster(RoomNo,RoomType,Prize) Values('101','Single','50$')
  Insert into HotelMaster(RoomNo,RoomType,Prize) Values('102','Double','80$')

select * from HotelMaster  
  
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'RoomBooking' )    
DROP TABLE RoomBooking    
GO    
    
CREATE TABLE RoomBooking    
(    
    BookingID int identity(1,1), 
    RoomID int ,  
    BookedDateFR VARCHAR(20)  NOT NULL , 
    BookedDateTO VARCHAR(20)  NOT NULL ,
   BookingStatus VARCHAR(100) NOT NULL,  
  PaymentStatus VARCHAR(100) NOT NULL, 
  AdvancePayed VARCHAR(100) NOT NULL,
 TotalAmountPayed VARCHAR(100) NOT NULL,
CONSTRAINT [PK_RoomBooking] PRIMARY KEY CLUSTERED          
(         
  [BookingID] ASC    
   
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]         
) ON [PRIMARY]       
  
select * from RoomBooking  

Stored Procedure

Run all this Procedure one by one in your SQL Server:

SQL
USE HotelDB    
GO       

-- =============================================    
-- To Select all Hotels   
-- EXEC USP_HotelMaster_Select ''  
-- =============================================    
CREATE PROCEDURE [dbo].[USP_HotelMaster_Select]     
(    
     @RoomNo            VARCHAR(100)     = ''      
      )         
AS                                                                  
BEGIN         
        SELECT  RoomID,RoomNo , RoomType,Prize
        FROM HotelMaster  
        WHERE  
                RoomNo like  @RoomNo +'%'  
                 Order By RoomNo
END 

-- To insert
-- EXEC [USP_Hotel_Insert] ''  
-- =============================================                                
CREATE PROCEDURE [dbo].[USP_Hotel_Insert]                                                
   ( 
     @RoomNo            VARCHAR(100)     = '',  
     @RoomType      VARCHAR(100)     = '',
      @Prize      VARCHAR(100)     = ''
      )                                                          
AS                                                                  
BEGIN         
        IF NOT EXISTS (SELECT * FROM HotelMaster WHERE RoomNo=@RoomNo)  
            BEGIN  
  
                INSERT INTO HotelMaster (RoomNo,RoomType,Prize)
                                     VALUES   (@RoomNo,@RoomType,@Prize)
                                 
                    Select 'Inserted' as results  
                          
            END  
         ELSE  
             BEGIN  
                     Select 'Exists' as results  
              END  
  
END  
                                                 
-- =============================================    
-- To Select all RoomBooking  
-- EXEC USP_RoomBooking_SelectALL ''  
-- =============================================    
CREATE PROCEDURE [dbo].[USP_RoomBooking_SelectALL]     
(    
     @RoomID            VARCHAR(100)     = ''      
      )         
AS                                                                  
BEGIN         
        SELECT   A.RoomNo,
                B.BookingID, 
                B.RoomID ,  
                B.BookedDateFR, 
                B.BookedDateTO, 
                B.BookingStatus ,  
                B.PaymentStatus,  
                B.AdvancePayed, 
                B.TotalAmountPayed 
        FROM HotelMaster A
            Inner join RoomBooking B
            ON A.RoomID=B.RoomID
        WHERE  
                A.RoomID like  @RoomID +'%'  
          
END 
 
-- To insert
-- EXEC USP_RoomBooking_Insert ''  
-- =============================================                                
CREATE PROCEDURE [dbo].[USP_RoomBooking_Insert]                                                
   (                         
     @BookingID  VARCHAR(100)     = '',  
     @RoomID   VARCHAR(100)     = '',    
    @BookedDateFR  VARCHAR(100)     = '',  
    @BookedDateTO  VARCHAR(100)     = '',  
    @BookingStatus   VARCHAR(100)     = '',    
    @PaymentStatus  VARCHAR(100)     = '',   
    @AdvancePayed VARCHAR(100)     = '',  
    @TotalAmountPayed   VARCHAR(100)     = '' 
      )                                                          
AS                                                                  
BEGIN       
        IF NOT EXISTS (SELECT * FROM RoomBooking WHERE RoomID=@RoomID )
            BEGIN  
  
                INSERT INTO RoomBooking
           (RoomID ,  BookedDateFR,  BookedDateTO, BookingStatus , _
            PaymentStatus, AdvancePayed, TotalAmountPayed )
     VALUES
            ( @RoomID ,  @BookedDateFR,  @BookedDateTO, @BookingStatus , _
              @PaymentStatus, @AdvancePayed, @TotalAmountPayed )
                                 
                    Select 'Inserted' as results  
                          
            END  
         ELSE  
             BEGIN  
                     UPDATE  RoomBooking
                     SET     BookedDateFR     = @BookedDateFR , 
                            BookedDateTO     = @BookedDateTO, 
                            BookingStatus    = @BookingStatus,  
                            PaymentStatus    = @PaymentStatus,  
                            AdvancePayed     = @AdvancePayed, 
                            TotalAmountPayed = @TotalAmountPayed
                         WHERE   
                        RoomID = @RoomID
                              
               Select 'Updated' as results  
                      
              END   
END  

                                                    
-- =============================================    
-- To Select all user roles   
-- EXEC USP_RoomBooking_Delete ''  
-- =============================================   
Create PROCEDURE [dbo].[USP_RoomBooking_Delete]                                                
   (  
     @BookingID       VARCHAR(20)     = ''
      )                                                          
AS                                                                  
BEGIN         
         Delete from  RoomBooking  WHERE  BookingID  = @BookingID                 
            Select 'Deleted' as results  
END  

-- =============================================    
-- To Select all Hotels   
-- EXEC USP_HotelStatus_Select ''  
-- =============================================    
Create PROCEDURE [dbo].[USP_HotelStatus_Select]     
(    
     @RoomNo            VARCHAR(100)     = ''      
      )         
AS                                                                  
BEGIN         
       SELECT   A.RoomNo,          
               ISNULL(B.BookedDateFR, '' ) as BookedDateFR, 
               ISNULL(B.BookedDateTO, '' ) as BookedDateTO, 
               ISNULL(B.BookingStatus, 'Free' ) as BookingStatus,  
               ISNULL(B.PaymentStatus, '' ) as PaymentStatus,  
               ISNULL(B.AdvancePayed, '0' ) as AdvancePayed, 
               ISNULL(B.TotalAmountPayed, '0$' ) as TotalAmountPayed
        FROM HotelMaster A
        Left Outer join RoomBooking B
        ON A.RoomNo=B.RoomID
        Order By  A.RoomNo
END 

Create Your MVC Web Application in Visual Studio 2015

After installing our Visual Studio 2015, click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.

Image 6

Select MVC, WEB API and click OK.

Image 7

Add Database using ADO.NET Entity Data Model

Right click our project and click Add, then New Item. Select Data, then ADO.NET Entity Data Model and give the name for our EF and click:

Image 8

Select "EF Designer from database" and click Next.

Image 9

Click on New Connection to connect our SQL Server database.

Image 10

Connect to our database. Click Next to select our Tables and Stored Procedure for Menu management.

Image 11

Now select all our tables and Stored procedure details and click Finish.

Image 12

Procedure to Add Our Web API Controller

Right-click the Controllers folder, click Add and then click Controller.

Image 13

Select Web API 2 Controller – Empty, click Add and give name for our WEB API controller.

Image 14

Working with WEBAPI Controller for CRUD

Select Controller and add an Empty Web API 2 Controller. Provide your name to the Web API controller and click OK. Here for our Web API Controller, we have given the name “HotelAPIController".

As we have created Web API controller, we can see our controller has been inherited with ApiController.

As we all know, Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.

Web API has the following four methods as Get/Post/Put and Delete where:

  • Get is to request for the data (Select)
  • Post is to create a data (Insert)
  • Put is to update the data
  • Delete is to delete data

Get Method

In our example, I have used only a Get method since I am using only a Stored Procedure. We need to create an object for our Entity and write our Get method to do Select/Insert/Update and Delete operations.

Select Operation

We use a get method to get all the details of the both AlbumMaster and MusicDetail tables using an entity object and we return the result as IEnumerable. We use this method in our AngularJS and display the result in an MVC page from the AngularJS controller. Using Ng-Repeat, we can bind the details.

Here, we can see in the getHotelRooms method we have passed the search parameter to the USP_HotelMaster_Select Stored Procedure. In the Stored Procedure, we used like "%" to return all the records if the search parameter is empty.

C#
// To select Hotel Details
        [HttpGet]
        public IEnumerable<USP_HotelMaster_Select_Result> getHotelRooms(string RoomNo)
        {
            if (RoomNo == null)
                RoomNo = "";
            return objapi.USP_HotelMaster_Select(RoomNo).AsEnumerable();
        }

Insert Operation

Similar to select, we passed all the parameters to the insert procedure. This insert method will return the result from the database as a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.

C#
// To insert Hotel Room Details
        [HttpGet]
        public IEnumerable<string> insertHotelRoom
               (string RoomNo, string RoomType, string Prize)
        {
            if (RoomNo == null)
                RoomNo = "";

            if (RoomType == null)
                RoomType = "";

            if (Prize == null)
                Prize = "";

            return objapi.USP_Hotel_Insert(RoomNo, RoomType, Prize).AsEnumerable();
        }

Similar to Hotel Room, we will be using the methods for Room Booking Details to perform our CRUD operations . Here is the code for Select, Insert, Update and Delete.

C#
// to Search all Room Booking Details
        [HttpGet]
        public IEnumerable<USP_RoomBooking_SelectALL_Result> 
               getRoomBookingDetails(string RoomID)
        {
            if (RoomID == null)
                RoomID = "";

            return objapi.USP_RoomBooking_SelectALL(RoomID).AsEnumerable();
        }

        // to Search all Room Dashbard Details
        [HttpGet]
        public IEnumerable<USP_HotelStatus_Select_Result> 
               getRoomDashboardDetails(string RoomNo)
        {
            if (RoomNo == null)
                RoomNo = "";
            
            return objapi.USP_HotelStatus_Select(RoomNo).AsEnumerable();
        }

        // To Insert /Update Room Booking
        [HttpGet]
        public IEnumerable<string> insertRoomBooking
        (string BookingID, string RoomID, string BookedDateFR, 
         string BookedDateTO, string BookingStatus, string PaymentStatus, 
         string AdvancePayed, string TotalAmountPayed)
        {
            if (BookingID == null)
                BookingID = "0";

            if (RoomID == null)
                RoomID = "0";

            if (BookedDateFR == null)
            {
                BookedDateFR = "";
            }
                else
            {
                BookedDateFR = BookedDateFR.Substring(0, 10);
            }

            if (BookedDateTO == null)
            {
                BookedDateTO = "";
            }
            else
            {
                BookedDateTO = BookedDateTO.Substring(0, 10);
            }

            if (BookingStatus == null)
                BookingStatus = "";

            if (PaymentStatus == null)
                PaymentStatus = "";

            if (AdvancePayed == null)
                AdvancePayed = "";

            if (TotalAmountPayed == null)
                TotalAmountPayed = "";

            return objapi.USP_RoomBooking_Insert(BookingID, RoomID, 
            BookedDateFR, BookedDateTO, BookingStatus, PaymentStatus, 
            AdvancePayed, TotalAmountPayed).AsEnumerable();
        }
        // To Delete Music Details
        [HttpGet]
        public IEnumerable<string> deleteROom(string BookingID)
        {
            if (BookingID == null)
                BookingID = "0";

            return objapi.USP_RoomBooking_Delete(BookingID).AsEnumerable();
        }

Next, we will create our AngularJs Controller and view page to perform our CRUD operations to manage both Hotel Room and Room Booking.

Room/Room Booking CRUD

Image 15

Creating AngularJS Controller

Firstly, create a folder inside the Scripts folder and we have given the folder name “MyAngular”.

Image 16

Now add your Angular Controller inside the folder.

Right click the MyAngular folder and click Add and New Item. Select Web and then AngularJS Controller and provide a name for the Controller. I have named my AngularJS Controller “Controller.js”.

Image 17

Once the AngularJS Controller is created, we can see by default, the controller will have the code with the default module definition and all.

If the AngularJS package is missing, then add the package to your project.

Right click your MVC project and click Manage NuGet Packages.

Image 18

Search for AngularJS and click Install.

Image 19

Procedure to Create AngularJS Script Files

Modules.js: Here, we will add the reference to the AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.

JavaScript
// <reference path="../angular.js" />  
/// <reference path="../angular.min.js" />   
/// <reference path="../angular-animate.js" />   
/// <reference path="../angular-animate.min.js" />   
var app;
(function () {
    app = angular.module("AngularJs_Module", ['ngAnimate']);
})();

Controllers: In AngularJS Controller, I have done all the business logic and returned the data from Web API to our MVC HTML page.

1. Variable Declarations

Firstly, we declared all the local variables that need to be used.

JavaScript
app.controller("AngularJs_Controller", 
    function ($scope, $timeout, $rootScope, $window, $http) {
    $scope.date = new Date();
    $scope.MyName = "shanu";
    // For Hotel Room Details
    $scope.RoomID = 0;
    $scope.RoomNo = "";
    $scope.RoomType = "";
    $scope.Prize = "";

    // For Hotel Room Booking Details
    $scope.BookingID = 0;
    $scope.RoomIDs = "";
   
    $scope.BookedDateFR = $scope.date;
    $scope.BookedDateTO = $scope.date;
    $scope.BookingStatus = "";
    $scope.PaymentStatus = "";
    $scope.AdvancePayed = "0$";
    $scope.TotalAmountPayed = "0$";

Methods

Select Method

In the select method, we have used $http.get to get the details of both Room, Room Booking and Room Status to display on dashboard from Web API. In the get method, we will provide our API Controller name and method to get the details.

The final result will be displayed to the MVC HTML page using data-ng-repeat.

JavaScript
// This method is to get all the Room Details. 
    selectRoomDetails('');
    selectRoomBookingDetails('');

    selectAvailableStatus('');
    function selectRoomDetails(RoomNo) {
        $http.get('/api/HotelAPI/getHotelRooms/', 
        { params: { RoomNo: RoomNo } }).success(function (data) {
            $scope.HotelRoomData = data; 
            if ($scope.HotelRoomData.length > 0) {
            }
        })
   .error(function () {
       $scope.error = "An Error has occurred while loading posts!";
   });
    }

    function selectRoomBookingDetails(RoomID) {
        $http.get('/api/HotelAPI/getRoomBookingDetails/', 
        { params: { RoomID: RoomID } }).success(function (data) {
            $scope.RoomBookingData = data; 
            if ($scope.RoomBookingData.length > 0) {
            }
        })
  .error(function () {
      $scope.error = "An Error has occurred while loading posts!";
  });
    }

    function selectAvailableStatus(RoomNo) {
        $http.get('/api/HotelAPI/getRoomDashboardDetails/', 
        { params: { RoomNo: RoomNo } }).success(function (data) {
            $scope.RoomAvailableData = data;
            if ($scope.RoomAvailableData.length > 0) {
            }
        })
  .error(function () {
      $scope.error = "An Error has occurred while loading posts!";
  });
    }

Insert Room Detail

In this method, we pass all the user input room details to be inserted in database.

JavaScript
//Save Hotel Room
    $scope.saveRoom = function () {
        $scope.IsFormSubmitted2 = true; 
        $scope.Message = ""; 
        if ($scope.IsFormValid2 = false) { 
             $http.get('/api/HotelAPI/insertHotelRoom/', 
             { params: { RoomNo: $scope.RoomNo, RoomType: $scope.RoomType, 
             Prize: $scope.Prize } }).success(function (data) {
                    $scope.roomInserted = data;
                    alert($scope.roomInserted);
                    cleardetails();
                    selectRoomDetails('');
                })
         .error(function () {
             $scope.error = "An Error has occurred while loading posts!";
         });            
        }
        else {
            $scope.Message = "All the fields are required.";
        }
    };

Room Status Dashboard Module

This is our main module where user can check all room status as Free/Occupied or reserved with all details.

Image 20

Here, we have created one more AngularJs Controller and named as HomeController. In this controller, we will get details of Albums and music to play our songs.

In home page, we display only 4 Room Status details in one row. To fix the four columns first in home page index view page, we add this CSS style.

In dashboard, we display the Room details depend on their status.

We have used three statuses for rooms as:

  1. Free (We use Green Color for Free Rooms)
  2. Occupied (We use Red Color for Occupied Rooms)
  3. Reserved (We use Yellow Color for Reserved Rooms)

In our dashboard View page, we add this Style to change the color depend on the Status.

In HTML part, we use this style in div tag to display four columns per row with Background color depending on the room status.

HTML
 <div class="columns">
         <div ng-repeat="details in RoomAvailableData">
                <table style='width: 99%;table-layout:fixed;'>
                     <tr ng-class="{actualColor: details.BookingStatus == 'Free',
                     changeColor1: details.BookingStatus == 'Occupied', 
                     changeColor2: Status == t;>
                            <td align="center" >
                                     <table style='width: 99%;table-layout:fixed;'>
                                         <tr>
                                             <td>&nbsp;</td>
                                         </tr>
                                         <tr>
                                         <td align="center">
                                             <b>Room NO : {{details.RoomNo}}</b>
                                         </td>
                                         </tr>
                                         <tr>
                                             <td align="center">
                                                 <b>Status : {{details.BookingStatus}}</b>
                                             </td>
                                         </tr>
                                         <tr>
                                             <td align="center">
                                                 <span style="font-size:medium">
                                                     Payment Status :<b> 
                                                     {{details.PaymentStatus}}</b>
                                                 </span>
                                             </td>
                                         </tr>
                                         <tr>
                                             <td align="center">
                                                 <span style="font-size:medium">
                                                     Advance Paid :<b> 
                                                     {{details.AdvancePayed}}</b>
                                                 </span>
                                             </td>
                                         </tr>
                                         <tr>
                                             <td align="center">
                                                 <span style="font-size:medium">
                                                     Total Amount Paid : 
                                                     <b>{{details.TotalAmountPayed}}</b>
                                                 </span>
                                             </td>
                                         </tr>
                                         <tr>
                                             <td align="center">
                                                 <span style="font-size:small">
                                                    Booked From  : {{details.BookedDateFR}} ~ 
                                                                   {{details.BookedDateTO}}
                                                 </span>
                                             </td>
                                         </tr>
                                         <tr>
                                             <td>&nbsp;</td>
                                         </tr>
                                     </table>
                                 </td>
                             </tr>
             </table>
         </div>
     </div>

Points of Interest

Hope you all like this Shanu Hotel Room Booking web based system.

This is a simple web based Hotel Room Booking developed using MVC and AngularJs. This application can be extended to add more features as per your requirement. Note in webconfig change as per your SQL Server setting before running this program and don’t forget to run all the SQL Queries attached with the zip file.

History

  • 21st October, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)