文档结构  
可译网翻译有奖活动正在进行中,查看详情 现在前往 注册?
原作者:syed shanu    来源:CodeProject [英文]
CY2    计算机    2016-10-29    0评/668阅
翻译进度:67%   参与翻译: zhongzhong (8), CY2 (4)

在这篇文章中,我们将学习如何创建一个简单的基于web的酒店房间预订系统, 使用 MVC, AngularJS, 和 WebAPI。

介绍

在这篇文章中,我们将学习如何创建一个简单的基于web的酒店房间预订系统, 使用 MVC, AngularJS, 和 WebAPI。

什么是SHANU酒店房间预订?

SHANU 酒店客房预订是一个基于Web的简单的酒店客房预订系统。 用户可以添加酒店房间的详细信息和房间预订日期。 SHANU酒店预订有两个模块1) 仪表板 2) 房间/预订 CRUD (添加房间和预订)。

第 1 段(可获 1.26 积分)

这个应用程序有两个模块

  1. 房间状态 (仪表板)
  2. 房间/预订 CRUD (添加房间和管理预订)

房间状态:  这是主要的仪表板模块。用户可以在仪表板页面查看所有的空闲/占用和预订房间信息。此模块将帮助用户轻松查看可用的空闲房间。 可用的空闲房间为绿色,占用的房间为红色,预留的房间为黄色。 这种颜色差异将有助于用户看到哪些房间是空闲的,占用了和被预留的。

在这个仪表板页面中,随着房间号和状态,我们也能看到详细信息,比如付款状态是未付还是已付,预先支付的金额,总金额和预定的时间从哪天到哪天。

第 2 段(可获 1.61 积分)

房间/预订CRUD (添加房间和管理预订):

在这个模块,我们将管理房间和房间预订信息。

房间详情页:

在这里用户可以添加房间细节和房间房号,房间类型和价格的细节。

房间/预订CRUD:

这是我们的主要部分,用户将以访客的身份预订房间。 在这里,我们选择房间号,预订日期,预订状态为免费,占用和保留,支付类型为支付,未支付和预付, 预付金额及已付总金额。 我们还可以编辑和删除预订细节。

先决条件

Visual Studio 2015: 你可以从这里下载它。

第 3 段(可获 1.33 积分)

代码

创建数据库和表

下面是用来创建数据库、表以及一些样本数据的 SQL 脚本。在你的 SQL Server 数据库中执行此脚本。我这里用的是 SQL Server 2014. 

-- =============================================                                  
-- 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  
第 4 段(可获 0.43 积分)

存储过程 : 在你的SQL Server上一个一个运行一下存储过程

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 
第 5 段(可获 0.16 积分)

在Visual Studio 2015中创建您的MVC Web应用程序

在安装我们的Visual Studio 2015后, 单击“开始”,然后程序并选择Visual Studio 2015 - Click Visual Studio 2015. 单击“新建”,然后选择“Web“项目,然后选择 ASP.NET Web Application. 请输入您的项目名称,然后单击“确定”。

选择MVC,Web API,点击OK。

添加使用ADO.NET实体数据模型的数据库

右键单击项目,单击 添加, 然后 新项目. 选择 数据,然后 ADO.NET Entity Data Model ,填写名称,然后点击增加

选择"EF Designer from database" 然后点击下一步.

单击新建连接来连接我们的SQL Server数据库.

第 6 段(可获 1.36 积分)

连接到我们的数据库。单击“下一步”选择菜单管理的表和存储过程.。

现在选择所有表和存储过程详细信息,然后单击“完成”.。

添加Web API控制器程序

右键单击 (Controller)控制器 文件夹, 单击“添加”,然后单击“控制器”。

选择Web API 2 Controller – Empty,点击添加并给我们的web API控制器命名。

处理 WEBAPI Controller 的 CRUD功能

选择控制器并添加一个空的Web API 2控制器。向Web API控制器提供您的名称,然后单击“确定”.。在这里为我们的Web API控制器名字为“HotelAPIController”。

我们已经创建了Web API控制器,我们可以看到我们的控制器已经继承了ApiController。

我们都知道Web API是一个简单和容易的方法来为浏览器和手机建立HTTP服务。
Web API有以下四种方法 GET/POST/PUT和DELETE:

第 7 段(可获 1.89 积分)
  • 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 AlbumMasater 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. 

第 8 段(可获 2.06 积分)
// 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();
}

插入操作

和select一样,我们将所有的参数传递给插入的存储过程。 这个insert方法将会返回数据库是否成功插入数据的结果。我们将得到结果,并从AngularJS的控制器显示到MVC应用中。 

第 9 段(可获 0.59 积分)
// 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();

}
同样是酒店房间,我们将使用这些方法来对房间预订详情做CRUD的操作,在这里就是代码中的Select(查询),Insert(插入),Update(更新)和Delete(删除)。
第 10 段(可获 0.36 积分)

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  

Creating AngularJS Controller

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

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”.

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

第 11 段(可获 1.38 积分)

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

Right click your MVC project and click Manage NuGet Packages.

Search for AngularJS and click Install.

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”. 

// <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']);
})();
第 12 段(可获 0.7 积分)

控制器: 在 AngularJS 的控制器中我们已经完成了所有的商业逻辑并从 Web API 中返回所需的数据给 MVC HTML 页面。

1. 变量声明

首先我们声明了即将要用到的本地变量:

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 Bookin Details
    $scope.BookingID = 0;
    $scope.RoomIDs = "";
   
    $scope.BookedDateFR = $scope.date;
    $scope.BookedDateTO = $scope.date;
    $scope.BookingStatus = "";
    $scope.PaymentStatus = "";
    $scope.AdvancePayed = "0$";
    $scope.TotalAmountPayed = "0$";
第 13 段(可获 0.46 积分)

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. 

// 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 occured 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 occured 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 occured while loading posts!";
  });
    }
第 14 段(可获 0.76 积分)

插入房间详情

在这个方法中我们传入了用户输入的房间详情信息,并插入到数据库中。

//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 occured while loading posts!";
         });

            
        }
        else {
            $scope.Message = "All the fields are required.";
        }
    };
第 15 段(可获 0.24 积分)

Room Status Dashboard Module:

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

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 4 column 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 3 status 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)
第 16 段(可获 1.55 积分)

在面板视图页面中,我们使用了不同颜色来标识不同的房间状态。

在 HTML 部分,我们在 div 标签中使用如下样式使得一行显示4列,每一个单元格的背景色是根据房间的状态来决定的。

<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: details.BookingStatus == 'Reserved'}">
                      <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>

 

第 17 段(可获 0.51 积分)

Points of Interest

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

This is 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 Query attached with the Zip file

第 18 段(可获 0.88 积分)

文章评论