一步一步asp.net_三层构架的学习

总结一下现在做的项目,由于混乱的项目经验,我就全部重新写了以前的一个项目,搭建的是简单三层架构的模式,简单三层是我第一个认识的架构层次的理念,也是影响非常深的,以前只是理论的学学什么设计模式,什么mvc,但是这些根本太遥远,因为没有编码经验,没有项目经验,永远也无法体会架构之美,更有甚者,认为这些架构太复杂了,还要花时间,仍然是那种业务数据UI混合的模式,然后混杂大量的增删改查,再加上大量的ctrl+c或者ctrl+v的代码,以至于面向对象的东西,做了大半年除了封装类,没有什么跟面向对象有关系的了.....纯属面向过程+class的模式.那么什么是面向对象,这个问题,太难回答了,面向对象,简单地说就是拿人的思维去解决问题.

  人的思维是复杂的,因此,有了复杂的分工,因此我们在学习面向对象的时候更重要的是想象着,

人怎么做?

回归正题:三层构架

三层构架,说到底就是一个简单的分层概念,一个数据访问层,业务逻辑层,和UI层,而我们经常见到的,

一步一步asp.net_三层构架的学习_第1张图片

BLL就是业务逻辑层,DAL就是数据访问层,czcraft网站就是所谓的UI层,而Model是什么呢?这和MVC的model又有什么区别?

model其实就是实体层,因为为了在BLL和DAL以及Ui层传输数据,我们要借助model这个实体层来传输数据,

比如我们注册一个帐号信息,

我们可以把所有收集到的帐号信息,保存在一个member的实体类中,然后传入给BLL处理.

BLL就是业务逻辑层,我们经常会遇到这样一个现象:

一个asp.net WebForm界面,一个事件大量的代码

一步一步asp.net_三层构架的学习_第2张图片

这种代码,如果一百个登录是不是要复制一百份,当我们复制的第二次就要考虑怎么复用.

这时候我们想象,为什么要把这些业务写到事件中?

我们首先要做的就是第一步分离,我们可以尝试定义一个类的方式,这是第一步的分离,设计一个member类,里面封装了,member的各种字段和方法,比如登录,等等,

一步一步asp.net_三层构架的学习_第3张图片

这是第一步的分离,这样的好处就是可以复用方法,不用复制复制再次复制,但是这样子逻辑和数据访问仍然写死在一个类中,如果我们要修改比如一个细节,

1.以前登陆都是明文,现在要加密,结果我们又要修改.

2.如果以前数据库删除一条会员信息,没有做级联删除(比如关联会员的其他信息,比如会员购买记录的信息等),现在要增加,结果又是大量的修改.

为什么我们不分理出数据和操作,以及UI显示?

我们分离出DAL,专门负责数据库操作,不管业务逻辑,BLL只负责业务逻辑,

当然为了考虑多种数据库的兼容设计,我们可以再加一层,IDAL接口层,

当然我们的数据库操作类也最好设计成兼容多种数据库的模式,

一步一步asp.net_三层构架的学习_第4张图片

关于DAL,BLL,我就举一个实例,比如会员信息,DAL的形式就是这样,

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using czcraft.Model;
   6:  using System.Data;
   7:  using System.Data.SqlClient;
   8:  using System.Data.Common;
   9:  namespace czcraft.DAL
  10:  /*
  11:   *   作者: Sweet
  12:   *  创建时间: 2012/5/5 10:13:44
  13:   *  类说明: czcraft.DAL
  14:   */ 
  15:  {
  16:       ///<summary>
  17:       ///member表DAL
  18:       ///</summary>
  19:      public partial class memberDAL
  20:      {
  21:          DBO.DBOperator SqlHelper = DBO.DBOperator.instance();
  22:          /// <summary>
  23:          /// 增加member
  24:          /// </summary>
  25:          /// <param name="model">tableName实体</param>
  26:          /// <returns>执行状态</returns>
  27:          public int AddNew(member model)
  28:          {
  29:              string sql="insert into member(username,password,Sex,nation,mobilephone,Telephone,Email,qq,Zipcode,Address,states,VCode,VTime) output inserted.Id values(@username,@password,@Sex,@nation,@mobilephone,@Telephone,@Email,@qq,@Zipcode,@Address,@states,@VCode,@VTime)";
  30:              int id=(int)SqlHelper.ExecuteScalar(sql
  31:                          ,(DbParameter)new SqlParameter("username",model.username)
  32:                          ,(DbParameter)new SqlParameter("password",model.password)
  33:                          ,(DbParameter)new SqlParameter("Sex",model.Sex)
  34:                          ,(DbParameter)new SqlParameter("nation",model.nation)
  35:                          ,(DbParameter)new SqlParameter("mobilephone",model.mobilephone)
  36:                          ,(DbParameter)new SqlParameter("Telephone",model.Telephone)
  37:                          ,(DbParameter)new SqlParameter("Email",model.Email)
  38:                          ,(DbParameter)new SqlParameter("qq",model.qq)
  39:                          ,(DbParameter)new SqlParameter("Zipcode",model.Zipcode)
  40:                          ,(DbParameter)new SqlParameter("Address",model.Address)
  41:                          ,(DbParameter)new SqlParameter("states",model.states)
  42:                          ,(DbParameter)new SqlParameter("VCode",model.VCode)
  43:                          ,(DbParameter)new SqlParameter("VTime",model.VTime)
  44:              );
  45:              return id;
  46:          }
  47:          /// <summary>
  48:          /// 更新member实体
  49:          /// </summary>
  50:          /// <param name="model">tableName实体</param>
  51:          /// <returns>执行状态</returns>
  52:          public bool Update(member model)
  53:          {
  54:              string sql="update member set username=@username,password=@password,Sex=@Sex,nation=@nation,mobilephone=@mobilephone,Telephone=@Telephone,Email=@Email,qq=@qq,Zipcode=@Zipcode,Address=@Address,states=@states where id=@id";
  55:          return SqlHelper.ExecuteNonQuery(sql
  56:                          ,(DbParameter)new SqlParameter("Id",model.Id)
  57:                          ,(DbParameter)new SqlParameter("username",model.username)
  58:                          ,(DbParameter)new SqlParameter("password",model.password)
  59:                          ,(DbParameter)new SqlParameter("Sex",model.Sex)
  60:                          ,(DbParameter)new SqlParameter("nation",model.nation)
  61:                          ,(DbParameter)new SqlParameter("mobilephone",model.mobilephone)
  62:                          ,(DbParameter)new SqlParameter("Telephone",model.Telephone)
  63:                          ,(DbParameter)new SqlParameter("Email",model.Email)
  64:                          ,(DbParameter)new SqlParameter("qq",model.qq)
  65:                          ,(DbParameter)new SqlParameter("Zipcode",model.Zipcode)
  66:                          ,(DbParameter)new SqlParameter("Address",model.Address)
  67:                          ,(DbParameter)new SqlParameter("states",model.states)
  68:                          //,(DbParameter)new SqlParameter("VCode",model.VCode)
  69:                          //,(DbParameter)new SqlParameter("VTime",model.VTime)
  70:              );
  71:          }
  72:          /// <summary>
  73:          /// 删除member
  74:          /// </summary>
  75:          /// <param name="id">id</param>
  76:          /// <returns>执行状态</returns>
  77:          public bool Delete(int id)
  78:          {
  79:          return SqlHelper.ExecuteNonQuery("delete from member where id=@id",
  80:                          (DbParameter)new SqlParameter("id",id));
  81:          }
  82:          /// <summary>
  83:          /// 删除member
  84:          /// </summary>
  85:          /// <param name="strID">strID,记得多个用,隔开</param>
  86:          /// <returns>执行状态</returns>
  87:          public bool DeleteMoreID(string strID)
  88:          {
  89:          return SqlHelper.ExecuteNonQuery("delete from member where id in ("+strID+")");
  90:          }
  91:          /// <summary>
  92:          /// 将DataRow转化为Model实体
  93:          /// </summary>
  94:          /// <param name="row">DataRow信息</param>
  95:          /// <returns>执行状态</returns>
  96:          private static member ToModel(DataRow row)
  97:          {
  98:              member model=new member();
  99:              model.Id =row.IsNull("Id")?null:(System.Int32?)row["Id"];
 100:              model.username =row.IsNull("username")?null:(System.String)row["username"];
 101:              model.password =row.IsNull("password")?null:(System.String)row["password"];
 102:              model.Sex =row.IsNull("Sex")?null:(System.String)row["Sex"];
 103:              model.nation =row.IsNull("nation")?null:(System.String)row["nation"];
 104:              model.mobilephone =row.IsNull("mobilephone")?null:(System.String)row["mobilephone"];
 105:              model.Telephone =row.IsNull("Telephone")?null:(System.String)row["Telephone"];
 106:              model.Email =row.IsNull("Email")?null:(System.String)row["Email"];
 107:              model.qq =row.IsNull("qq")?null:(System.String)row["qq"];
 108:              model.Zipcode =row.IsNull("Zipcode")?null:(System.String)row["Zipcode"];
 109:              model.Address =row.IsNull("Address")?null:(System.String)row["Address"];
 110:              model.states =row.IsNull("states")?null:(System.String)row["states"];
 111:              model.VCode =row.IsNull("VCode")?null:(System.String)row["VCode"];
 112:              model.VTime =row.IsNull("VTime")?null:(System.DateTime?)row["VTime"];
 113:              return model;
 114:          }
 115:          /// <summary>
 116:          /// 根据id获取tableName实体信息
 117:          /// </summary>
 118:          /// <param name="id">id</param>
 119:          /// <returns>执行状态</returns>
 120:          public member Get(int id)
 121:          {
 122:              DataTable dt=SqlHelper.ExecuteDataTable("select * from member where id=@id",
 123:  (DbParameter)new SqlParameter("id",id));
 124:              if(dt.Rows.Count>1){
 125:              throw new Exception("more than 1 row was found");
 126:              }
 127:              if(dt.Rows.Count<=0){return null;}
 128:              DataRow row=dt.Rows[0];
 129:              member model=ToModel(row);
 130:              return model;
 131:          }
 132:          /// <summary>
 133:          /// 列出tableName所有的实体信息
 134:          /// </summary>
 135:          /// <returns>执行状态</returns>
 136:          public IEnumerable<member> ListAll()
 137:          {
 138:              List<member> list=new List<member>();
 139:              DataTable dt=SqlHelper.ExecuteDataTable("select * from member");
 140:              foreach(DataRow row in dt.Rows){
 141:              list.Add(ToModel(row));
 142:              }
 143:              return list;
 144:          }
 145:   
 146:          /// <summary>
 147:          ///分页获取数据
 148:          /// </summary>
 149:          /// <param name="tableName">表名</param>
 150:          /// <param name="InnerJoin">内连接</param>
 151:          /// <param name="strGetFields">返回的列信息</param>
 152:           /// <param name="sortId">排序的列名</param>
 153:          /// <param name="PageSize">每页记录数</param>
 154:          /// <param name="PageIndex">页数</param>
 155:          /// <param name="OrderType">排序类型排序类型, 非0 值则降序</param>
 156:          /// <param name="strWhere">查询条件(注意: 不要加where) </param>
 157:          public IEnumerable<member> ListByPagination(string tableName,string InnerJoin,string strGetFields,string sortId,int PageSize,int PageIndex,string OrderType,string strWhere)
 158:          {
 159:              List<member> list=new List<member>();
 160:              DataTable dt=SqlHelper.ExecuteDataTable("exec[pagination]  @tableName,@InnerJoin,@strGetFields,@sortId,@PageSize,@PageIndex,@doCount,@OrderType,@strWhere",(DbParameter)new SqlParameter("tableName",tableName),(DbParameter)new SqlParameter("@InnerJoin",InnerJoin),(DbParameter)new SqlParameter("@strGetFields",strGetFields),(DbParameter)new SqlParameter("@sortId",sortId),(DbParameter)new SqlParameter("@PageSize",PageSize),(DbParameter)new SqlParameter("@PageIndex",PageIndex),(DbParameter)new SqlParameter("@doCount","0"),(DbParameter)new SqlParameter("@OrderType",OrderType),(DbParameter)new SqlParameter("@strWhere",strWhere));
 161:              foreach(DataRow row in dt.Rows){
 162:              list.Add(ToModel(row));
 163:              }
 164:              return list;
 165:          }
 166:          /// <summary>
 167:          ///获取表总记录个数(不用加where)
 168:          /// <param name="strWhere">查询条件(不用加where)</param>
 169:          /// <summary>
 170:          public int GetCount(string strWhere)
 171:          {
 172:              if(!string.IsNullOrEmpty(strWhere))
 173:              strWhere=" where "+strWhere;
 174:              return SqlHelper.ExecuteSelectFirstNum("select count(1) from member"+strWhere);
 175:          }
 176:      }
 177:  }

这里是用代码生成器生成的,我自己写的一个简单的代码生成器,为了学习代码生成器,专门设计了一个简单的,

这里注意,因为代码生成器的原因,我们必须把自己写的方法等,通过部分类的方式合并,所以,我们都要加上partial 关键字,这很重要

一步一步asp.net_三层构架的学习_第5张图片

可以看到DAL主要涉及的都是纯种的增删改查操作,他不用管具体有没有权限之类的,这些不是

他的活,为什么要他干?

接下来就是BLL层,业务逻辑层,我们经常碰到,前期不需要功能,后期增加进去,以前没有权限判断,以前没有加密要求,以前的加密太简单,现在要更改一种更好的方法,结果要修改好多东西,这样就全部写在业务逻辑层,他只负责业务逻辑的判断,然后提供给UI数据,

   1:   /// <summary>
   2:          /// 判定查询条件
   3:          /// </summary>
   4:          /// <param name="info"></param>
   5:          /// <returns></returns>
   6:          public static string ConfirmCondition(string info)
   7:          {
   8:              string condition = "";//查询条件
   9:              if (Tools.IsNumber(info)) //如果是数字,则查询id
  10:              {
  11:                  condition = "id like '%" + info + "%'";
  12:              }
  13:              else condition = "username like '%" + info + "%'"; //查询用户名
  14:              return condition;
  15:          }
  16:          /// <summary>
  17:          /// 检查用户名和邮箱
  18:          /// </summary>
  19:          /// <param name="UserName">用户名</param>
  20:          /// <param name="Email">邮箱</param>
  21:          /// <returns></returns>
  22:          public bool CheckUserNameAndEmail(string UserName,string Email)
  23:          {
  24:              memberDAL dal=new memberDAL ();
  25:              member info = dal.GetMemberInfo(UserName);
  26:              return Email==info.Email;
  27:          }
  28:          /// <summary>
  29:          /// 随机生成一个6位的密码
  30:          /// </summary>
  31:          /// <returns></returns>
  32:          public string CreateNewPwd() 
  33:          {
  34:              string Pwd="";
  35:              Random ran=new Random (DateTime.Now.Second);
  36:              for (int i = 0; i < 6; i++)
  37:              {
  38:                  Pwd += ran.Next(1, 10);
  39:              }
  40:              return Pwd;
  41:          }
  42:          /// <summary>
  43:          /// 修改密码
  44:          /// </summary>
  45:          /// <param name="UserName">用户名</param>
  46:          /// <param name="Pwd">密码</param>
  47:          /// <returns></returns>
  48:          public bool UpdatePwd(string UserName, string Pwd)
  49:          {
  50:              return new memberDAL().UpdatePassword(UserName, Tools.GetMD5(Pwd));
  51:          }
  52:          /// <summary>
  53:          /// 修改密码
  54:          /// </summary>
  55:          /// <param name="UserName">用户名</param>
  56:          /// <param name="oldPwd">旧密码</param>
  57:          /// <param name="newPwd">新密码</param>
  58:          /// <returns></returns>
  59:          public bool UpdatePassword(string UserName, string oldPwd, string newPwd)
  60:          {
  61:              memberDAL dal = new memberDAL();
  62:              string Pwd = dal.GetPassword(UserName);
  63:              if (Pwd == Tools.GetMD5(oldPwd))
  64:              {
  65:                  //加密并且更新
  66:                 return dal.UpdatePassword(UserName, Tools.GetMD5(newPwd));
  67:              }
  68:              return false;
  69:          }
  70:           /// <summary>
  71:          /// 更新member实体
  72:          /// </summary>
  73:          /// <param name="model">member实体</param>
  74:          /// <param name="IsUserNameUpdate">是否采用用户名更新</param>
  75:          /// <returns></returns>
  76:          public bool UpdateUserInfo(member model)
  77:          {
  78:             return new memberDAL().Update(model, true);
  79:          }
  80:          /// <summary>
  81:          /// 检验用户名是否存在
  82:          /// </summary>
  83:          /// <param name="userName"></param>
  84:          /// <returns></returns>
  85:          public bool CheckExistUserName(string userName)
  86:          {
  87:              return new memberDAL().GetCount(string.Format(" username='{0}'", userName)) == 0;
  88:          }
  89:          /// <summary>
  90:          /// 验证用户信息
  91:          /// </summary>
  92:          /// <param name="UserName">用户名</param>
  93:          /// <param name="GuidInfo">guid随机码</param>
  94:          public bool ActivationMemberNumber(string UserName, string GuidInfo)
  95:          {
  96:              memberDAL dal = new memberDAL();
  97:              //获取过期时间
  98:              DateTime dt = dal.GetMemberVTime(UserName, GuidInfo);
  99:              //如果已经过期
 100:              if (dt < DateTime.Now)
 101:              {
 102:                  return false;
 103:              }
 104:              else
 105:              {
 106:                  //激活帐号
 107:                 return  dal.ActivationMemberStatus(UserName);
 108:              }
 109:          }
 110:          /// <summary>
 111:          /// 用户登录
 112:          /// </summary>
 113:          /// <param name="info">会员model</param>
 114:          /// <returns></returns>
 115:          public bool MemberLogin(member info)
 116:          {
 117:              info.password = Tools.GetMD5(info.password);
 118:              return new memberDAL().MemberLogin(info);
 119:          }
 120:          /// <summary>
 121:          /// 检验密码是否正确
 122:          /// </summary>
 123:          /// <param name="UserName">用户名</param>
 124:          /// <param name="Password">密码</param>
 125:          /// <returns></returns>
 126:          public bool CheckPwd(string UserName, string Password)
 127:          {
 128:              //先不加密,以后全部都要加密
 129:              string Pwd = Tools.GetMD5(new memberDAL().GetPassword(UserName));
 130:              if (Password == Pwd)
 131:              {
 132:                  return true;
 133:              }
 134:              else
 135:                  return false;
 136:          }
 137:          /// <summary>
 138:          /// 返回验证组件的数组格式(Validate)
 139:          /// </summary>
 140:          /// <param name="fieldId">字段</param>
 141:          /// <param name="Status">状态</param>
 142:          /// <param name="errorMsg">错误消息(没有则"")</param>
 143:          /// <returns></returns>
 144:          public string ReturnValueValidateAjax(string fieldId, bool Status, string errorMsg)
 145:          {
 146:             
 147:              if (string.IsNullOrEmpty(errorMsg))
 148:              {
 149:                  return "[\"" + fieldId + "\",\"" + Status + "\"]";
 150:              }
 151:              return "[\"" + fieldId + "\",\"" + Status + "\",\""+errorMsg+"\"]";
 152:          
 153:          }
 154:   
 155:          /// <summary>
 156:          /// 返回给客户端的json格式数据(用于根据用户登录状态决定)
 157:          /// </summary>
 158:          /// <param name="info"></param>
 159:          /// <returns></returns>
 160:          public string ReturnJson(member info, out bool Status)
 161:          {
 162:              //登录状态
 163:              Status = MemberLogin(info);
 164:              //生成json格式数据
 165:              return WriteJsonForReturn(Status, info.username);
 166:   
 167:          }
 168:          /// <summary>
 169:          /// 记住帐号和密码的枚举
 170:          /// </summary>
 171:          public enum RememberType
 172:          {
 173:              /// <summary>
 174:              /// 记住帐号
 175:              /// </summary>
 176:              RememberName = 0,
 177:              /// <summary>
 178:              /// 同时记住帐号和密码
 179:              /// </summary>
 180:              RememberNameAndPwd = 1,
 181:              /// <summary>
 182:              /// 不记住帐号密码
 183:              /// </summary>
 184:              NoRemember = 2
 185:          }
 186:   
 187:          /// <summary>
 188:          /// 根据保存帐号密码状态判断是保存帐号还是同时保存帐号和密码
 189:          /// </summary>
 190:          /// <param name="IsSaveName">"1"代表保存,"0"代表不保存</param>
 191:          /// <param name="IsSavePwd">"1"代表保存,"0"代表不保存</param>
 192:          /// <returns></returns>
 193:          public RememberType GetRememberType(string IsSaveName, string IsSavePwd)
 194:          {
 195:              RememberType SaveType = RememberType.NoRemember;
 196:   
 197:              //保存帐号和密码
 198:              if (IsSaveName.Equals("1") && IsSavePwd.Equals("1"))
 199:              {
 200:                  SaveType = RememberType.RememberNameAndPwd;
 201:              }
 202:              //保存帐号
 203:              if (IsSaveName.Equals("1") && !IsSavePwd.Equals("1"))
 204:              {
 205:                  SaveType = RememberType.RememberName;
 206:              }
 207:              else if (!IsSaveName.Equals("1"))
 208:              {
 209:                  SaveType = RememberType.NoRemember;
 210:              }
 211:              return SaveType;
 212:          }
 213:          /// <summary>
 214:          /// 根据用户名获取用户信息(返回json数据)
 215:          /// </summary>
 216:          /// <param name="UserName">用户名</param>
 217:          /// <returns></returns>
 218:          public string GetMemberInfoByJson(string UserName)
 219:          {
 220:              bool Status = false;
 221:              member info = new memberDAL().GetMemberInfo(UserName);
 222:              if (info.Id.HasValue)
 223:              {
 224:                  Status = true;
 225:              }
 226:              StringBuilder json = new StringBuilder();
 227:              StringWriter sw = new StringWriter(json);
 228:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
 229:              {
 230:                  jsonWriter.Formatting = Formatting.Indented;
 231:                  jsonWriter.WriteStartObject();
 232:                  jsonWriter.WritePropertyName("Status");
 233:                  jsonWriter.WriteValue(Status);
 234:                  jsonWriter.WritePropertyName("Data");
 235:                  jsonWriter.WriteStartArray();
 236:                  jsonWriter.WriteStartObject();
 237:                  jsonWriter.WritePropertyName("UserName");
 238:                  jsonWriter.WriteValue(info.username);
 239:                  jsonWriter.WritePropertyName("Sex");
 240:                  jsonWriter.WriteValue(info.Sex);
 241:                  jsonWriter.WritePropertyName("Nation");
 242:                  jsonWriter.WriteValue(info.nation);
 243:                  //mobilephone Telephone Email qq Zipcode Address
 244:                  jsonWriter.WritePropertyName("MobilePhone");
 245:                  jsonWriter.WriteValue(info.mobilephone);
 246:                  jsonWriter.WritePropertyName("TelePhone");
 247:                  jsonWriter.WriteValue(info.Telephone);
 248:                  jsonWriter.WritePropertyName("Email");
 249:                  jsonWriter.WriteValue(info.Email);
 250:                  jsonWriter.WritePropertyName("QQ");
 251:                  jsonWriter.WriteValue(info.qq);
 252:                  jsonWriter.WritePropertyName("ZipCode");
 253:                  jsonWriter.WriteValue(info.Zipcode);
 254:                  //地址处理
 255:   
 256:                  string[] strAddresss = GetSplitAddress(info.Address);
 257:                  string Province = "";
 258:                  string City = "";
 259:                  string Country = "";
 260:                  string Address = "";
 261:                  if (strAddresss.Count() > 0)
 262:                  {
 263:                      Province = strAddresss[0];
 264:                      City = strAddresss[1];
 265:                      Country = strAddresss[2];
 266:                      Address = strAddresss[3];
 267:   
 268:                  }
 269:                  jsonWriter.WritePropertyName("Province");
 270:                  jsonWriter.WriteValue(Province);
 271:                  jsonWriter.WritePropertyName("City");
 272:                  jsonWriter.WriteValue(City);
 273:                  jsonWriter.WritePropertyName("Country");
 274:                  jsonWriter.WriteValue(Country);
 275:                  jsonWriter.WritePropertyName("Address");
 276:                  jsonWriter.WriteValue(Address);
 277:                  jsonWriter.WriteEndObject();
 278:   
 279:                  jsonWriter.WriteEndArray();
 280:                  jsonWriter.WriteEndObject();
 281:              }
 282:              return json.ToString();
 283:          }
 284:          /// <summary>
 285:          /// 地址分割(将用户信息表中的地址分割成 省(编号) 市(编号) 县(编号) 家住址
 286:          /// </summary>
 287:          /// <param name="Address">地址</param>
 288:          /// <returns></returns>
 289:          public string[] GetSplitAddress(string Address)
 290:          {
 291:              string[] str = Address.Split('|');
 292:              return str;
 293:          }
 294:          /// <summary>
 295:          /// 检查用户登录状态,用于验证自动登录(并返回json格式)
 296:          /// </summary>
 297:          /// <returns></returns>
 298:          public string CheckLoginStatus(out bool Status)
 299:          {
 300:   
 301:              //登录状态
 302:              Status = true;
 303:              string UserName = Common.CookieHelper.GetCookieValue("UserName");
 304:              //如果cookies为空,直接返回
 305:              if (Tools.IsNullOrEmpty(UserName))
 306:              {
 307:                  Status = false;
 308:              }
 309:              string Pwd = Common.CookieHelper.GetCookieValue("Pwd");
 310:              if (Tools.IsNullOrEmpty(Pwd))
 311:              {
 312:                  Status = false;
 313:              }
 314:              else
 315:              {
 316:                  //查找该用户真实密码,并进行md5加密
 317:                  string password = new memberDAL().GetPassword(UserName);
 318:                  //如果两次密码相同则可以自动登陆了
 319:                  if (password!=Pwd)
 320:                  {
 321:                      Status = false;
 322:                  }
 323:              }
 324:   
 325:              //生成json格式数据
 326:              return WriteJsonForReturn(Status, UserName);
 327:          }
 328:          /// <summary>
 329:          /// 为用户登录写入json数据
 330:          /// </summary>
 331:          /// <param name="Status">登录状态</param>
 332:          /// <param name="UserName">用户名</param>
 333:          /// <returns></returns>
 334:          public string WriteJsonForReturn(bool Status, string UserName)
 335:          {
 336:              StringBuilder json = new StringBuilder();
 337:              StringWriter sw = new StringWriter(json);
 338:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
 339:              {
 340:                  jsonWriter.Formatting = Formatting.Indented;
 341:                  jsonWriter.WriteStartObject();
 342:                  jsonWriter.WritePropertyName("Status");
 343:                  jsonWriter.WriteValue(Status);
 344:                  jsonWriter.WritePropertyName("UserName");
 345:                  jsonWriter.WriteValue(UserName);
 346:                  jsonWriter.WriteEndObject();
 347:              }
 348:              return json.ToString();
 349:          }
 350:          /// <summary>
 351:          /// 记住用户信息
 352:          /// </summary>
 353:          /// <param name="Type">记住用户信息类别</param>
 354:          /// <returns></returns>
 355:          public bool RememberUserInfo(member info, RememberType type)
 356:          {
 357:              if (type == RememberType.RememberName)
 358:              {
 359:                  //记住帐号7天
 360:                  CookieHelper.SetCookie("UserName", info.username, DateTime.Now.AddDays(7));
 361:              }
 362:              else if (type == RememberType.RememberNameAndPwd)
 363:              {
 364:   
 365:                  //md5哈希加密
 366:                  string sercret = Tools.GetMD5(info.password);
 367:                  //同时记住帐号和密码7天
 368:                  CookieHelper.SetCookie("UserName", info.username, DateTime.Now.AddDays(7));
 369:                  CookieHelper.SetCookie("Pwd", sercret, DateTime.Now.AddDays(7));
 370:              }
 371:              else
 372:              {
 373:                  return false;
 374:              }
 375:              return true;
 376:   
 377:          }
 378:   
 379:   
 380:      }
 381:  }

 

可以看到,这里没有任何数据库的操作,他只负责业务逻辑判断,然后给UI提供数据.

而web的UI层,我们以前经常性碰到这样的代码,

   1:    /// <summary>
   2:      /// 网页中间显示的涵数condiction显示条件,nums显示行数
   3:      /// </summary>
   4:      /// <param name="condiction"></param>
   5:      /// <param name="nums"></param>
   6:      public void Show(string condiction, int nums)
   7:      {
   8:   
   9:          string sql = "";
  10:          //还要修改
  11:          string id = "";
  12:          string picturepath = "";
  13:          string name = "";
  14:          string appreciation = "";
  15:          string reward = "";
  16:          string title = "";
  17:          string time = "";
  18:          string ArticleHtmlUrl = "";
  19:          StringBuilder content = new StringBuilder();//高效率拼接字符串
  20:          if (condiction == "大师风采")
  21:          {
  22:              sql = "select top " + nums + " hit,id,name,appreciation,Reward,Picturepath from master  where state='1' and state1='1' order by master.rank desc";
  23:              DataTable dt = cs.GetDataSet(sql).Tables[0];
  24:   
  25:   
  26:              for (int i = 0; i < dt.Rows.Count; i++)
  27:              {
  28:                 id = dt.Rows[i]["id"].ToString();
  29:                 picturepath = dt.Rows[i]["Picturepath"].ToString();
  30:                  picturepath = GetPicturePath(picturepath);
  31:                 name = dt.Rows[i]["name"].ToString();
  32:   
  33:                 //appreciation = GetTile(dt.Rows[i]["appreciation"].ToString().Replace("<br>","\r\n"));
  34:                 //reward = GetTile(dt.Rows[i]["Reward"].ToString().Replace("<br>", "\r\n"));
  35:                  if (i == 0) {
  36:                      content.Append("<div class='r_s_p m_border'>");
  37:                  }
  38:                  else
  39:                  {
  40:                      content.Append("<div class='r_s_p'>");
  41:                  }
  42:                      content.Append("<div class='gk_pic'><img src='" + picturepath + "' alt='" + dt.Rows[i]["name"].ToString() + "'/></div>");
  43:   
  44:                  content.Append("<div class='master_p'>");
  45:   
  46:                  content.Append("<p><strong><a href='Masterintro.aspx?id=" + id + "'>" + name + "</a></strong></p>");
  47:   
  48:                  content.Append("<div class='honor'><ul>");
  49:   
  50:                  content.Append("<li><a href='Masterintro.aspx?id=" + id + "'>" + appreciation + "</a></li>");
  51:   
  52:                  content.Append("<li><a href='Masterintro.aspx?id=" + id + "'>" + reward + "</a></li>");
  53:                  content.Append("</ul></div></div></div>");
  54:   
  55:                  content.Append("<div class='master_border'>&nbsp;</div>");
  56:   
  57:              }
  58:   
  59:              Response.Write(content.ToString());
  60:              return;
  61:   
  62:          }
  63:   
  64:   
  65:   
  66:   
  67:          if (condiction == "业内新闻")
  68:          {
  69:              sql = "select top " + nums + " id,title,time,ArticleHtmlUrl from news order by time desc";
  70:              DataTable dt = cs.GetDataSet(sql).Tables[0];
  71:              //if (dt.Rows.Count == 0)
  72:              //{
  73:              //    content.Append("<li><a href='#'>#</a><span class='time'>[##-##-##]</span></li>");
  74:              //}
  75:              for (int i = 0; i < dt.Rows.Count; i++)
  76:              {
  77:   
  78:                 title = GetTile(dt.Rows[i]["title"].ToString());
  79:   
  80:                  id = dt.Rows[i]["id"].ToString();
  81:   
  82:                  time = ((DateTime)dt.Rows[i]["time"]).Date.ToShortDateString();
  83:   
  84:                  ArticleHtmlUrl = dt.Rows[i]["ArticleHtmlUrl"].ToString();
  85:   
  86:                  content.Append("<li><a href='NewsContent.aspx?id="+id+"'>" + title + "</a><span class='time'>[" + time + "]</span></li>");
  87:   
  88:              }
  89:              Response.Write(content.ToString());
  90:   
  91:              return;
  92:   
  93:          }
  94:          if (condiction == "工艺知识")
  95:          {
  96:   
  97:              sql = "select top " + nums + " id,title,time,ArticleHtmlUrl from craftknowledge order by time desc";
  98:   
  99:              DataTable dt = cs.GetDataSet(sql).Tables[0];
 100:   
 101:              //if (dt.Rows.Count == 0)
 102:              //{
 103:              //    content.Append("<li><a href='#'>#</a><span class='time'>[##-##-##]</span></li>");
 104:              //}
 105:              for (int i = 0; i < dt.Rows.Count; i++)
 106:              {
 107:   
 108:                 title = GetTile(dt.Rows[i]["title"].ToString());
 109:   
 110:                  id = dt.Rows[i]["id"].ToString();
 111:   
 112:                  time = ((DateTime)dt.Rows[i]["time"]).Date.ToShortDateString();
 113:   
 114:                  ArticleHtmlUrl = dt.Rows[i]["ArticleHtmlUrl"].ToString();
 115:   
 116:                  //Response.Write("<li><a href='craftknowledge_info.aspx?craft_id=" + id + "'>" + title + "</a><span class='time'>[" + time + "]</span></li>");
 117:   
 118:                  content.Append("<li><a href='craftknowledge_info.aspx?id=" + id + "'>" + title + "</a><span class='time'>[" + time + "]</span></li>");
 119:   
 120:              }
 121:              Response.Write(content.ToString());
 122:              return;
 123:   
 124:          }
 125:   
 126:          if (condiction == "企业展示")
 127:          {
 128:              sql = "select top " + nums + " hit, id,name from company where state='1' and state1='1' order by company.rank desc";
 129:   
 130:              DataTable dt = cs.GetDataSet(sql).Tables[0];
 131:              //if (dt.Rows.Count == 0)
 132:              //{
 133:              //    content.Append("<li><a href='#'>#</a></li>");
 134:              //}
 135:              for (int i = 0; i < dt.Rows.Count; i++)
 136:              {
 137:                 id = dt.Rows[i]["id"].ToString();
 138:   
 139:                 name = GetTile(dt.Rows[i]["name"].ToString());
 140:   
 141:   
 142:   
 143:                 content.Append("<li><a href='company_introduce.aspx?id=" + id + "'>" + name + "</a></li>");
 144:   
 145:              }
 146:              Response.Write(content.ToString());
 147:              return;
 148:   
 149:          }
 150:      }

这种UI和数据混合的方式,如果界面一修改,改动大了,经常性碰到,这个界面太囧了......然后改整个版面,为什么我们不把数据和UI隔离开来,后台么?

只负责数据提供,通过JSON等传输,然后前台js/JQuery操作界面呢?

这样前台就应该这样,

   1:  <%@ Page Language="C#" MasterPageFile="~/InfoPage.master" AutoEventWireup="true"
   2:      CodeFile="MasterInfo.aspx.cs" Inherits="Master_MasterInfo" Title="大师信息" %>
   3:   
   4:  <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
   5:      <link href="../css/gs_ms.css" rel="stylesheet" type="text/css" />
   6:   
   7:      <script src="../Admin/scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
   8:   
   9:      <script src="../js/queryUrlParams.js" type="text/javascript"></script>
  10:   
  11:      <script src="MasterInfo.js" type="text/javascript"></script>
  12:   
  13:      
  14:      <script type="text/javascript">
  15:     //获得大师id信息
  16:       var id=$.query.get("MasterId"); 
  17:      </script>
  18:   
  19:  </asp:Content>
  20:  <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  21:      <div class="ms">
  22:          <div class="ms_top">
  23:              <div class="m_load">
  24:                  <span><a href="../Default.aspx">首页</a> > <a href="MasterList.aspx">大师风采</a> > 大师</span></div>
  25:              <div class="mst_c">
  26:                  <ul class="mst_ul">
  27:                      <li><a href="#" id="Master_Intro">
  28:                          <p class="hide">
  29:                              大师简介</p>
  30:                      </a></li>
  31:                      <li><a href="#" id="Master_Award">
  32:                          <p class="hide">
  33:                              获奖情况</p>
  34:                      </a></li>
  35:                      <li><a href="#" id="Master_Work">
  36:                          <p class="hide">
  37:                              大师作品</p>
  38:                      </a></li>
  39:                  </ul>
  40:                  <div class="mst_img">
  41:                      <img src="../images/master_img.png" id="imgMaster" /></div>
  42:                  <div class="mst_xx">
  43:                      <table width="252" height="141" id="tbMasterInfo">
  44:                      </table>
  45:                  </div>
  46:              </div>
  47:          </div>
  48:          <div class="gs_nr" id="MasterContent">
  49:            
  50:          </div>
  51:      </div>
  52:  </asp:Content>

然后通过jquery操作,

   1:   
   2:       $(function(){
   3:       GetMasterInfo();
   4:       GetMasterIntro();
   5:       //绑定获取大师简介事件
   6:       $("#Master_Intro").click(function(){
   7:       GetMasterIntro();
   8:       });
   9:       $("#Master_Award").click(function(){
  10:       GetMasterReward();
  11:       });
  12:       $("#Master_Work").click(function(){
  13:       GetMasterWork();
  14:       });
  15:       });
  16:      //获取大师基本信息
  17:      function GetMasterInfo(){
  18:      $.ajax({
  19:      url:"Data/MasterInfo.ashx?method=GetMasterInfo&MasterId="+id,
  20:      type:"post",
  21:      success:function(text){
  22:       var jsonData=$.parseJSON(text);
  23:       if(jsonData.Status){             
  24:        var item='<tr><td width="51"> 姓名:</td>';
  25:        item+=' <td width="92">'+jsonData.Data[0].Name+'</td>';
  26:        item+='<td width="47">性别: </td>';
  27:        item+='<td width="42">'+jsonData.Data[0].Sex+'</td>';
  28:        item+=' </tr>';
  29:        item+='<tr> <td> 出生:</td>';
  30:        item+='<td>'+jsonData.Data[0].Birthday+'</td>';
  31:        item+='</tr>';
  32:        item+=' <tr><td colspan="4">艺术家分类:';
  33:        item+=jsonData.Data[0].TypeName;
  34:        item+='</td></tr>';
  35:        
  36:        $("#tbMasterInfo").empty();
  37:        $("#tbMasterInfo").append(item);
  38:          var src="../Admin/FileManage/GetImg.ashx?method=GetMasterPic&type=medium&fileName="+jsonData.Data[0].PicturePath;
  39:        $("#imgMaster").attr("src",src);
  40:       }
  41:      }
  42:      });
  43:      
  44:      }
  45:      //获取大师简介信息
  46:       function GetMasterIntro(){
  47:        $.ajax({
  48:      url:"Data/MasterInfo.ashx?method=GetMasterIntro&MasterId="+id,
  49:      type:"post",
  50:      success:function(text){
  51:        var jsonData=$.parseJSON(text);
  52:       if(jsonData.Status){     
  53:         var item='<h4>大师简介</h4>';
  54:         item+='<p>'+jsonData.Data[0].Introduction+'</p>';
  55:        $("#MasterContent").empty();
  56:        $("#MasterContent").append(item);
  57:         }
  58:        }
  59:        });
  60:       }
  61:       //获取大师荣誉信息
  62:       function GetMasterReward(){
  63:    $.ajax({
  64:      url:"Data/MasterInfo.ashx?method=GetMasterReward&MasterId="+id,
  65:      type:"post",
  66:      success:function(text){
  67:        var jsonData=$.parseJSON(text);
  68:        var item='<h4>大师荣誉</h4>';
  69:       if(jsonData.Status){     
  70:         item+='<ul class="gs_reward">';
  71:         item+=' <li>'+jsonData.Data[0].Reward+'</li></ul>';
  72:         item+=' <h4>获奖情况</h4><ul class="gs_cup">';
  73:        $.each(jsonData.Data[0].CertPicList,function(key,value){
  74:          var img="../Admin/FileManage/GetImg.ashx?method=GetMasterCert&type=medium&fileName="+value.CertPic;
  75:        item+='<li><span class="c_pic_a">';
  76:       item+='<img src='+img+' alt='+value.CertName+' title='+value.CertName+'/></span><span class="a_title">'+value.CertName+'</span>';
  77:        item+='</li>';
  78:        });
  79:        item+='</ul>';
  80:       
  81:         }
  82:         else{
  83:          item+=' <h4>获奖情况</h4>';
  84:         }
  85:          $("#MasterContent").empty();
  86:        $("#MasterContent").append(item);
  87:        }
  88:        });
  89:       }
  90:       //获取大师产品信息
  91:    function GetMasterWork(){
  92:    $.ajax({
  93:      url:"Data/MasterInfo.ashx?method=GetMasterWork&MasterId="+id,
  94:      type:"post",
  95:      success:function(text){
  96:        var jsonData=$.parseJSON(text);
  97:       var item='';
  98:       if(jsonData.Status){ 
  99:       $.each(jsonData.Data,function(key,value){    
 100:         item+='<h4>'+value.TypeName+'</h4>';
 101:         item+='<ul class="gs_pic">';
 102:           $.each(value.Product,function(PKey,PValue){
 103:                 var img="../Admin/FileManage/GetImg.ashx?method=GetMainProductPic&type=medium&fileName="+PValue.Picturepath;
 104:                 item+='<li>';
 105:                    item+='<a href="../Product/Product.aspx?ProductId='+PValue.ProductId+'" class="c_pic_a"><img src="'+img+'" alt="'+PValue.Name+'" title="'+PValue.SimpleName+'"/></a>';
 106:                    item+='<a href="../Product/Product.aspx?ProductId='+PValue.ProductId+'" class="a_title">'+PValue.SimpleName+'<br/><span class="rad2">¥'+PValue.Lsprice+'</span></a> ';
 107:                 item+='</li>';
 108:                               })
 109:         item+='</ul>';
 110:         item+='<div style="text-align:right"><a href="../Product/Master_MoreProduct.aspx?MasterId=' + id + '&&TypeId=' + value.TypeId + '">more>></a></div>';
 111:        
 112:         })
 113:      
 114:        }
 115:        else{
 116:        item+='没有数据!';
 117:        }
 118:          $("#MasterContent").empty();
 119:        $("#MasterContent").append(item);
 120:        }
 121:        });
 122:       }
 123:       

这样不管怎么改界面,我们的数据是不变的,哈哈!

 

还有最最最重要的,我们的代码规范,命名规范,我的所有代码全部自己强制性要求自己必须遵

守,所以才能一目了然,清晰,严谨,易于维护和开发!

今天的三层就总结到这里!

还有项目中比较重要的一些东西,下次在总结!

你可能感兴趣的:(asp.net)