65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 N 层架构的实时 MVC 应用程序

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.85/5 (10投票s)

2016 年 1 月 10 日

CPOL

3分钟阅读

viewsIcon

45048

downloadIcon

2745

引言

本文介绍如何使用 N 层架构创建实时 MVC Web 应用程序。全文将通过一个示例客户信息解决方案进行讲解。

模块

  • 使用 SQL Server 创建 SampleCustomerInformation 数据库
  • 使用 Visual Studio 2013 创建一个空的 MVC Web 应用程序(表示层)
    • 创建控制器、视图以及所需的相应 HTML 和 Javascript
  • 向解决方案中添加另一个项目,用于处理来自 SQL Server 的数据。创建一个 C# 类库项目(数据访问层)
    • 添加一个实体数据模型以连接到数据库。
    • 创建类以处理来自业务服务层的所有请求
    • 在业务服务层编写必要的方法来处理请求
  • 向解决方案中添加另一个项目,用于编写业务逻辑。创建一个 WCF 服务库
    • 向项目中添加必要的服务参数,以编写业务逻辑
    • 编写必要的操作合同,供表示层调用
    • 使用数据访问层中的所有可用方法来处理服务层中的数据
  • 为解决方案中的项目添加必要的引用
  • 为表示层添加服务引用
    • 使用服务层中的所有可用方法并处理请求。

使用的技术

  1. ASP.Net MVC5
  2. SQL Server 2014
  3. C# v5
  4. jQuery 2.14
  5. HTML5
  6. CSS3

IDE - Visual Studio 2013

使用代码

模块: 1 - 使用 SQL Server 创建 SampleCustomerInformation 数据库

/****** Object:  Database [SampleCustomerInformation]******/
CREATE DATABASE [SampleCustomerInformation]

Create table CustomerInformation(
SNO int not null identity(0,1),
CustomerID int not null primary key,
[First Name] varchar(50) not null,
[Last Name] varchar(50) not null,
Email varchar(60) null,
Phone varchar(13) not null,
[User Name] varchar(60) not null,
[Password] varchar(12) not null)

Create table CustomerLoginActivity(
SNO int not null identity(0,1),
[User Name] int not null,
[Password] varchar(60) not null,
[Login Time] Date not null
)

模块: 2 - 使用 Visual Studio 2013 创建一个空的 MVC Web 应用程序(表示层)

创建控制器、视图以及所需的相应 HTML 和 Javascript

在这里,我使用了 ajax jQuery 将数据从视图发送到控制器

ajax 请求可以使用的一些属性

  • Method: 指定操作类型(例如 GET、POST)
  • Url: 指定方法的路径
  • Data: 指定需要从视图传输到控制器进行处理的数据
  • Success: 指定成功时需要执行的一组语句
  • Failure: 指定失败时需要执行的一组语句

有关 jQuery Ajax 的更多信息,请访问 jQuery Ajax

HTML

<html>
<head>
    <title>Welcome</title>
    <script src="~/Scripts/jquery-2.1.4.min.js"></script>
    <script src="~/Scripts/HomeScript.js"></script>
</head>
<body>
    <form style="float:left">
        <h4>Sign Up</h4>
        <table>
            <tr>
                <td>First Name</td>
                <td><input type="text" name="firstName" id="firstName" placeholder="First Name" value="" required /></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><input type="text" name="lastName" id="lastName" placeholder="Last Name" value="" required /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" name="email" id="email" placeholder="Email" value="" required /></td>
            </tr>
            <tr>
                <td>Phone Number</td>
                <td><input type="text" name="phoneNumber" placeholder="Phone Number" id="phoneNumber" value="" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password" placeholder="Password" id="password" value="" /></td>
            </tr>
            <tr>
                <td>Confirm Password</td>
                <td><input type="password" name="confirmPassword" placeholder="Confirm Password" id="confirmPassword" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="btnRegister" id="btnRegister" value="Register" /></td>
            </tr>
        </table>
    </form>
    <div style="float:left">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <form style="float:left">
        <h4>Login</h4>
        <table>
            <tr>
                <td>User Name</td>
                <td><input type="text" name="userName" placeholder="Email" id="userName" value="" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="loginPassword" placeholder="Password" id="loginPassword" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="btnLogin" id="btnLogin" value="Login" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

Javascript

$(document).ready(function () {
    $("#btnRegister").click(function () {
        RegisterCustomer();
    });

    $("#btnLogin").click(function () {
        LoginCustomer();
    });
});

function RegisterCustomer() {
    var firstName = $("#firstName").val();
    var lastName = $("#lastName").val();
    var email = $("#email").val();
    var phoneNumber = $("#phoneNumber").val();
    var password = $("#password").val();
    var confirmPassword = $("#confirmPassword");

//Attributes in "data" of ajax request should match the arguments defined in the method in controller
    $.ajax({
        method: "POST",
        url: "../Home/RegisterCustomer",
        data: {
            firstName: firstName,
            lastName: lastName,
            email: email,
            phoneNumber: phoneNumber,
            password: password
        }
    }).done(function (msg) {
        if (msg == "success")
            alert("Login Successful");
        else
            alert("Login Failed: " + msg);
    });
}

function LoginCustomer() {
    var userName = $("#userName").val();
    var loginPassword = $("#loginPassword").val();

    $.ajax({
        method: "GET",
        url: "../Home/LoginCustomer",
        data: {
            userName: userName,
            loginPassword: loginPassword
        }
    })
    .done(function (msg) {
        alert("Login Activity Saved");
    });
}

 

模块: 3 - 向解决方案中添加另一个项目,用于处理来自 SQL Server 的数据。创建一个 C# 类库项目(数据访问层)

  • 创建类以处理来自业务服务层的所有请求
  • 在业务服务层编写必要的方法来处理请求
public class RegisterCustomerDataAccessLayer
    {
        #region Register Customer
        public bool RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)
        {
            try
            {
                using (var dbContext = new SampleCustomerInformationEntities())
                {
                    CustomerInformation newCustomer = new CustomerInformation();
                    newCustomer.CustomerID = 2;
                    newCustomer.First_Name = firstName;
                    newCustomer.Last_Name = lastName;
                    newCustomer.Email = email;
                    newCustomer.Phone = phoneNumber;
                    newCustomer.Password = password;
                    newCustomer.User_Name = email;
                    dbContext.CustomerInformations.Add(newCustomer);
                    dbContext.SaveChanges();
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion 
}

public class CustomerLoginDataAccessLayer
    {
        #region Customer Login
        public bool LoginCustomer(string userName, string loginPassword)
        {
            try
            {
                using (var dbContext = new SampleCustomerInformationEntities())
                {
                    CustomerInformation customer = new CustomerInformation();
                    customer = dbContext.CustomerInformations.FirstOrDefault(x => x.User_Name == userName && x.Password == loginPassword);
                    if (customer != null)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }

模块: 4 - 向解决方案中添加另一个项目,用于编写业务逻辑。创建一个 WCF 服务库

服务协约定义了从服务终结点可供客户端使用的所有方法或操作。服务协约是一个接口,它告诉客户端服务可以做什么。

操作协约定义在服务协约内部,并包含返回类型和参数。这些操作协约实现在继承了服务接口的类中。客户端可以使用此方法来执行操作。

数据协约描述了需要交换的信息,并可用于任何操作协约的参数或返回类型。基于参数和返回类型,数据将被序列化/反序列化到或从(二进制⇔XML)。

需要将 Data Member 属性应用于数据协约的所有成员,以指示其为数据成员,这意味着它应该被序列化。

有关 服务协约 的详细信息,请参阅 设计服务协约

有关 数据协约 的详细信息,请参阅 使用数据协约

  • 编写必要的操作合同,供表示层调用
  • 使用数据访问层中的所有可用方法来处理服务层中的数据
  [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request);

        [OperationContract]
        LoginCustomerRequest LoginCustomer(LoginCustomerRequest request);

        // TODO: Add your service operations here
    }



 public class Service1 : IService1
    {
        #region IService1 Members

        #region Register Customer
        public RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request)
        {
            try
            {
                var registerCustomerDal = new RegisterCustomerDataAccessLayer();
                var customer = registerCustomerDal.RegisterCustomer(request.FirstName, request.LastName, request.Email, request.PhoneNumber, request.Password);
                if (customer)
                    request.RegisterCustomerResponse = "Success";
                else
                    request.RegisterCustomerResponse = "Failure";
                return request;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            throw new NotImplementedException();
        }
        #endregion

        #region Login Customer
        public LoginCustomerRequest LoginCustomer(LoginCustomerRequest request)
        {
            try
            {
                var customerLoginDal = new CustomerLoginDataAccessLayer();
                var validateLogin = customerLoginDal.LoginCustomer(request.UserName, request.Password);
                if (validateLogin)
                    request.LoginCustomerResponse = "Login Successful";
                else
                    request.LoginCustomerResponse = "Login Failed";
                return request;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            throw new NotImplementedException();
        }
        #endregion
        #endregion
    }

模块: 6 - 为表示层添加服务引用

添加服务引用

  • 在客户端的“引用”文件夹上右键单击
  • 单击“添加服务引用”
  • 可以通过输入终结点 URL 或单击“发现”来查找服务引用
  • 选择所需的服务引用,即可访问所有可用的服务协约和操作协约。

有关使用 Web 服务的详细信息,请参阅 使用 Web 服务

Controller - 使用服务层中的所有可用方法并处理请求

 // GET: Home View
        public ActionResult Home()
        {
            return View();
        }

        //This method is used to register new customer
        //This method is passed as a url to the Ajax function RegisterCustomer()
        public string RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)
        {
            try
            {
                SampleCustomerInformationServiceReference.RegisterCustomerRequest request = new SampleCustomerInformationServiceReference.RegisterCustomerRequest();
                request.FirstName = firstName;
                request.LastName = lastName;
                request.Email = email;
                request.PhoneNumber = phoneNumber;
                request.Password = password;

                var response = client.RegisterCustomer(request);
                return response.RegisterCustomerResponse;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return "";
        }

        //This method is used to login a customer
        //This method is passed as a url to the Ajax function LoginCustomer()
        public string LoginCustomer(string userName, string loginPassword)
        {
            try
            {
                SampleCustomerInformationServiceReference.LoginCustomerRequest request = new SampleCustomerInformationServiceReference.LoginCustomerRequest();
                request.UserName = userName;
                request.Password = loginPassword;

                var response = client.LoginCustomer(request);
                return response.LoginCustomerResponse;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return "";
        }

如需演示,请下载项目并在本地运行。

© . All rights reserved.