您的位置:首页 > 运维架构 > 网站架构

使用三层架构实现简单的MVC登陆操作

2018-02-06 14:55 579 查看

转载:http://blog.csdn.net/agonie201218/article/details/44456847

对个别内容进行了修正!!!

一丶使用三层架构创建一个简单的MVC登录操作

   1.首先,创建一个项目以及BLL层、DAL层、Entity层,如图一:

                                          

图一

    2.创建一个数据库如图二:



图二

  3基本工作已做好,接下来就编BLL层、DAL层、Entity层。

     3.1先编Entity。Entity实体层(不属于三层架构的任意一层)定义一个类,主要用来保存以及传递数据库的信息。比如以图二的数据库为列,实体层代码如下:

   [csharp] view plain copy print?using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  
  
namespace Entity  
{  
    public class UserInfo  
    {  
          
        public int ID { get; set; }  
          
        [Required(ErrorMessage="用户名不能为空")]  
        public string UserName { get; set; }  
  
        [Required(ErrorMessage = "密码不能为空")]  
        public string UserPWD { get; set; }  
    }  
}  

  这样就定义了一个实体层(定义的字段和数据库里的一样)。

 3.2 DAL层。DAL只提供基本的数据访问,在其内定义增删改查!比如登录(查)代码如下:

[csharp] view plain copy print?using Entity;  
using System;  
using System.Collections.Generic;  
using System.Configuration;  
using System.Data;  
using System.Data.SqlClient;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace DAL  
{  
    public class UserService  
    {  
        //获取用户信息  
        public UserInfo GetUser(string userName)  
        {  
                string sql ="select * from userinfo where UserName=@username ";  
                SqlParameter[] param = new SqlParameter[]{  
                new SqlParameter("@username",userName),  
                };  
  
                // 执行  
                 UserInfo user =new UserInfo ();  
  
                 using (SqlDataReader sdr = SqlHelper.ExecuteReader(sql, param))  
                 {  
                     while(sdr.Read())  
                     {  
                         user.UserName = sdr["UserName"].ToString();  
                         user.UserPWD = sdr["UserPwd"].ToString();  
                     }  
  
                       return user;  

            }  
        }  
    }  
}  

  首先得引入Entity,其次,需要注意的是必须把UserService这个类定义为public类型的,否则BLL层访问不到。代码就不一一解读了,多是一些很基础的语句。
注:1.SqlHelper是一个已经封装好的类,专门执行sql语句。这里也可以自己写sql执行语句。
public static SqlDataReader ExecuteReader(string sql,params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(constr);
using( SqlCommand cmd = new SqlCommand(sql, con)){
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
con.Close();
con.Dispose();
throw;
}
}
}
2.须在web.config 里配置链接字符串。
<connectionStrings>
<add name="connstr" connectionString="Data Source=.;Initial Catalog=testdb;Integrated Security=True"/>
</connectionStrings>


  3.3BLL层:

  [csharp] view plain copy print?using DAL;  
using Entity;  
using System;  
using System.Collections.Generic;  
using System.Data;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace BLL  
{  
    public class UserManager  
    {  
        public bool Login(string userName, string userPWD)  
        {  
            // 业务逻辑层 调用 数据访问层  
            UserService service = new UserService();  
            UserInfo user =  service.GetUser(userName);  
            if (user == null || user.UserPWD != userPWD)  
            {  
                return false;  
            }  
            else  
            {  
                return true;  
            }  
        }  
    }  
}  

  首先还是得引入Entity和DAL。。。负责处理业务逻辑。通过获取UI传来的用户指令,执行业务逻辑,在需要访问数据源的时候,直接交个DAL进行处理。处理完成后,返回必要数据给UI。其实BLL层很简单,

4.设计简单的登陆页面

[html] view plain copy print?<head>
<script src="../MVCDemo/Scripts/jquery-1.10.2.js"></sctipt>
</head>
<body>  
    <div>  
     <form action="@Url.Content("~/Home/DoLogin")" method="post">  
        <table>  
            <tr>  
                <td>用户名</td>  
                <td>  
                   <input name="username" placeholder="用户名"required/>  
                </td>  

            </tr>  
            <tr>  
                <td>用户密码</td>  
                <td>  
                    <input name="userpwd" type="password"  placeholder="用户密码" required/>  
                </td>  
            </tr>  
            <tr>  
                <td colspan="2">  
                    <input type="submit" value="登陆" />  
                </td> 
                <td>@Html.ValidationMessage("info")  </td>   
            </tr>  
        </table>  
    </form>  
         
    </div>  
</body>  
注释:action="@Url.Content("~/Home/DoLogin")" method="post" 内~/Home/DoLogin",为“~/controller/action/”
也可以使用:@using (Html.BeginForm("DoLogin","Home")) {} 会生成一个表单,连接到对应Action Controller里面。

5.输入账号密码,点击提交按钮,将值交到控制器的DoLogin:

 
[csharp] view plain copy print?[httppost]
public ActionResult DoLogin(string username,string userpwd)  
       {  
           // model 验证失败  
           if (!ModelState.IsValid)  
           {  
                 
               return View();  
           }  
           else  
           {  
              if (new UserManager().Login(username, userpwd))  
              {  
                 return Content("<script>alert('登入成功!!!');location.href='index';</script>");  
              }  
              else {   
                  ModelState.AddModelError("info", "用户名或密码错误!!!");  
                  return View();  
              }  
  
           }  
             

6.运行结果:


二丶实现增删改查

  其实学会了登录功能后其他增删改查功能都是差不多的。只不过就是换了个sql语句,换汤不换药。我就不一一介绍了。三、思路login.cshtml内input为name="username"和name="userpwd"的值  --(传入控制器)--》HomeControl内[httppost] actionResult.Dologin()。Dologin()内调用业务逻辑层,业务逻辑层再调用数据访问层
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: