一步一步asp.net_ajax学习

继续ajax,今天的任务是做一个大师信息的页面,大致的静态页面

一步一步asp.net_ajax学习_第1张图片

一步一步asp.net_ajax学习_第2张图片

一步一步asp.net_ajax学习_第3张图片

以前的做法大致是先做一个大师的母板页,然后分成3个页面,分开做,不过那样重用性太低了,数据库语句也不注意性能优化,导致查询非常慢,而且用户体验不好,这次考虑用ajax做,并且优化查询.

 

要实现的功能:

1.首先ajax加载大师基本信息(包括姓名,性别,出生年月,分类,以及大师头像)

2.然后写三个ajax事件响应大师作品,大师简介,获奖情况,

3.默认进入此页面加载大师简介信息

 

主要的难点:

1.通过js获取html中的参数,比如一个大师列表页调转过来,传递的参数:MasterInfo.aspx?MasterId=xxxxx

我们需要通过js获取这个MasterId参数

2.ajax加载图片回调

3.最难的地方在大师作品,因为大师有多种类别的作品,我们只能获取每种作品的前8位显示出来,这个涉及到数据库查询优化,以前都是通过两次查询或者嵌套查询,性能非常低,这次需要生成json数据,前台JQuery调用也比较复杂.

 

实现:

1.js获取html中的参数,到网上看了一下,看到一个蛮不错的脚本,获取html参数

   1:  new function(settings) {
   2:    var $separator = settings.separator || '&';
   3:    var $spaces = settings.spaces === false ? false : true;
   4:    var $suffix = settings.suffix === false ? '' : '[]';
   5:    var $prefix = settings.prefix === false ? false : true;
   6:    var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
   7:    var $numbers = settings.numbers === false ? false : true;
   8:    
   9:    jQuery.query = new function() {
  10:      var is = function(o, t) {
  11:        return o != undefined && o !== null && (!!t ? o.constructor == t : true);
  12:      };
  13:      var parse = function(path) {
  14:        var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
  15:        while (m = rx.exec(match[2])) tokens.push(m[1]);
  16:        return [base, tokens];
  17:      };
  18:      var set = function(target, tokens, value) {
  19:        var o, token = tokens.shift();
  20:        if (typeof target != 'object') target = null;
  21:        if (token === "") {
  22:          if (!target) target = [];
  23:          if (is(target, Array)) {
  24:            target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
  25:          } else if (is(target, Object)) {
  26:            var i = 0;
  27:            while (target[i++] != null);
  28:            target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
  29:          } else {
  30:            target = [];
  31:            target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
  32:          }
  33:        } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
  34:          var index = parseInt(token, 10);
  35:          if (!target) target = [];
  36:          target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
  37:        } else if (token) {
  38:          var index = token.replace(/^\s*|\s*$/g, "");
  39:          if (!target) target = {};
  40:          if (is(target, Array)) {
  41:            var temp = {};
  42:            for (var i = 0; i < target.length; ++i) {
  43:              temp[i] = target[i];
  44:            }
  45:            target = temp;
  46:          }
  47:          target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
  48:        } else {
  49:          return value;
  50:        }
  51:        return target;
  52:      };
  53:      
  54:      var queryObject = function(a) {
  55:        var self = this;
  56:        self.keys = {};
  57:        
  58:        if (a.queryObject) {
  59:          jQuery.each(a.get(), function(key, val) {
  60:            self.SET(key, val);
  61:          });
  62:        } else {
  63:          jQuery.each(arguments, function() {
  64:            var q = "" + this;
  65:            q = q.replace(/^[?#]/,'');
  66:            q = q.replace(/[;&]$/,'');
  67:            if ($spaces) q = q.replace(/[+]/g,' ');
  68:            
  69:            jQuery.each(q.split(/[&;]/), function(){
  70:              var key = decodeURIComponent(this.split('=')[0] || "");
  71:              var val = decodeURIComponent(this.split('=')[1] || "");
  72:              
  73:              if (!key) return;
  74:              
  75:              if ($numbers) {
  76:                if (/^[+-]?[0-9]+\.[0-9]*$/.test(val))
  77:                  val = parseFloat(val);
  78:                else if (/^[+-]?[0-9]+$/.test(val))
  79:                  val = parseInt(val, 10);
  80:              }
  81:              
  82:              val = (!val && val !== 0) ? true : val;
  83:              
  84:              if (val !== false && val !== true && typeof val != 'number')
  85:                val = val;
  86:              
  87:              self.SET(key, val);
  88:            });
  89:          });
  90:        }
  91:        return self;
  92:      };
  93:      
  94:      queryObject.prototype = {
  95:        queryObject: true,
  96:        has: function(key, type) {
  97:          var value = this.get(key);
  98:          return is(value, type);
  99:        },
 100:        GET: function(key) {
 101:          if (!is(key)) return this.keys;
 102:          var parsed = parse(key), base = parsed[0], tokens = parsed[1];
 103:          var target = this.keys[base];
 104:          while (target != null && tokens.length != 0) {
 105:            target = target[tokens.shift()];
 106:          }
 107:          return typeof target == 'number' ? target : target || "";
 108:        },
 109:        get: function(key) {
 110:          var target = this.GET(key);
 111:          if (is(target, Object))
 112:            return jQuery.extend(true, {}, target);
 113:          else if (is(target, Array))
 114:            return target.slice(0);
 115:          return target;
 116:        },
 117:        SET: function(key, val) {
 118:          var value = !is(val) ? null : val;
 119:          var parsed = parse(key), base = parsed[0], tokens = parsed[1];
 120:          var target = this.keys[base];
 121:          this.keys[base] = set(target, tokens.slice(0), value);
 122:          return this;
 123:        },
 124:        set: function(key, val) {
 125:          return this.copy().SET(key, val);
 126:        },
 127:        REMOVE: function(key) {
 128:          return this.SET(key, null).COMPACT();
 129:        },
 130:        remove: function(key) {
 131:          return this.copy().REMOVE(key);
 132:        },
 133:        EMPTY: function() {
 134:          var self = this;
 135:          jQuery.each(self.keys, function(key, value) {
 136:            delete self.keys[key];
 137:          });
 138:          return self;
 139:        },
 140:        load: function(url) {
 141:          var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
 142:          var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
 143:          return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
 144:        },
 145:        empty: function() {
 146:          return this.copy().EMPTY();
 147:        },
 148:        copy: function() {
 149:          return new queryObject(this);
 150:        },
 151:        COMPACT: function() {
 152:          function build(orig) {
 153:            var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
 154:            if (typeof orig == 'object') {
 155:              function add(o, key, value) {
 156:                if (is(o, Array))
 157:                  o.push(value);
 158:                else
 159:                  o[key] = value;
 160:              }
 161:              jQuery.each(orig, function(key, value) {
 162:                if (!is(value)) return true;
 163:                add(obj, key, build(value));
 164:              });
 165:            }
 166:            return obj;
 167:          }
 168:          this.keys = build(this.keys);
 169:          return this;
 170:        },
 171:        compact: function() {
 172:          return this.copy().COMPACT();
 173:        },
 174:        toString: function() {
 175:          var i = 0, queryString = [], chunks = [], self = this;
 176:          var encode = function(str) {
 177:            str = str + "";
 178:            if ($spaces) str = str.replace(/ /g, "+");
 179:            return encodeURIComponent(str);
 180:          };
 181:          var addFields = function(arr, key, value) {
 182:            if (!is(value) || value === false) return;
 183:            var o = [encode(key)];
 184:            if (value !== true) {
 185:              o.push("=");
 186:              o.push(encode(value));
 187:            }
 188:            arr.push(o.join(""));
 189:          };
 190:          var build = function(obj, base) {
 191:            var newKey = function(key) {
 192:              return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
 193:            };
 194:            jQuery.each(obj, function(key, value) {
 195:              if (typeof value == 'object') 
 196:                build(value, newKey(key));
 197:              else
 198:                addFields(chunks, newKey(key), value);
 199:            });
 200:          };
 201:          
 202:          build(this.keys);
 203:          
 204:          if (chunks.length > 0) queryString.push($hash);
 205:          queryString.push(chunks.join($separator));
 206:          
 207:          return queryString.join("");
 208:        }
 209:      };
 210:      
 211:      return new queryObject(location.search, location.hash);
 212:    };
 213:  }(jQuery.query || {});

然后我们可以通过这么调用它

image

2.关于图片回调还是涉及到以前做的图片公共管理简化了操作,我们只需要很简单的向GetImg.ashx请求图片,根据type尺寸,fileName和到底调用哪个方法来获取不同的图片

image

 

3.关于这个类别分组查询,去年我做的一个网页比赛中就遇到过,以前是这两个

一步一步asp.net_ajax学习_第4张图片一步一步asp.net_ajax学习_第5张图片

分别是全国省市内容加载和红色事件加载,都只需要一条查询语句就能查询结果,利用了分组查询,蛮有意思的,

大致的语句

select id,title,isnull(histroytime,0) as month from(select

id,title,histroytime,row_number() over(partition by histroytime order by

histroytime) total from redCalendar) rn where rn.total<5

 

其实就是row_number和分组的用法

 

然后在程序中判断

 

 

 

 

程序主要代码:

前台:

   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>

处理加载的ajax的js文件:

   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:       if(jsonData.Status){     
  69:         var item='<h4>大师荣誉</h4>';
  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:        $("#MasterContent").empty();
  81:        $("#MasterContent").append(item);
  82:         }
  83:        }
  84:        });
  85:       }
  86:       //获取大师产品信息
  87:    function GetMasterWork(){
  88:    $.ajax({
  89:      url:"Data/MasterInfo.ashx?method=GetMasterWork&MasterId="+id,
  90:      type:"post",
  91:      success:function(text){
  92:        var jsonData=$.parseJSON(text);
  93:      
  94:       if(jsonData.Status){ 
  95:       var item='';
  96:       $.each(jsonData.Data,function(key,value){    
  97:         item+='<h4>'+value.TypeName+'</h4>';
  98:         item+='<ul class="gs_pic">';
  99:           $.each(value.Product,function(PKey,PValue){
 100:                 var img="../Admin/FileManage/GetImg.ashx?method=GetMainProductPic&type=medium&fileName="+PValue.Picturepath;
 101:                 item+='<li>';
 102:                    item+='<a href="../Product/Product.aspx?ProductId='+PValue.ProductId+'" class="c_pic_a"><img src="'+img+'" alt="'+PValue.Name+'" title="'+PValue.SimpleName+'"/></a>';
 103:                    item+='<a href="../Product/Product.aspx?ProductId='+PValue.ProductId+'" class="a_title">'+PValue.SimpleName+'<br/><span class="rad2">¥'+PValue.Lsprice+'</span></a> ';
 104:                 item+='</li>';
 105:                               })
 106:         item+='</ul>';
 107:         item+='<div style="text-align:right"><a href="../Product/Master_MoreProduct.aspx?MasterId=' + id + '&&TypeId=' + value.TypeId + '">more>></a></div>';
 108:        
 109:         })
 110:        $("#MasterContent").empty();
 111:        $("#MasterContent").append(item);
 112:        }
 113:        }
 114:        });
 115:       }
 116:       
类别分组的DAL方法:
   1:   /// <summary>
   2:          /// 通过大师id查找大师的产品(每种分别显示前8个)
   3:          /// </summary>
   4:          /// <param name="MasterId">大师id</param>
   5:          /// <returns></returns>
   6:          public DataTable ListAllByMasterIdToDatable(string MasterId)
   7:          {
   8:              return SqlHelper.ExecuteDataTable("select * from(select *,row_number() over (partition by TypeId order by TypeId) total from VProductCraftType where Masterid=@Masterid and Belongstype='0') rn where rn.total<=8", (DbParameter)new SqlParameter("Masterid", MasterId));
   9:          }
数据库的查询效果:
一步一步asp.net_ajax学习_第6张图片
BLL的主要业务逻辑处理:
下面第一个的业务逻辑是难点:
   1:     /// <summary>
   2:          /// 根据大师id查找大师的产品信息(每种分别显示前8个)
   3:          /// </summary>
   4:          /// <param name="MasterId">大师Id</param>
   5:          /// <returns></returns>
   6:          public string GetMasterWorkForJson(string MasterId)
   7:          {
   8:              //查询状态
   9:              bool Status = false;
  10:              //获取大师的产品信息(每种显示前8个)
  11:              DataTable dtListProduct = new VProductCraftTypeDAL().ListAllByMasterIdToDatable(MasterId);
  12:              //转化为json格式
  13:              StringBuilder json = new StringBuilder();
  14:              StringWriter sw = new StringWriter(json);
  15:              
  16:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
  17:              {
  18:                 
  19:                  jsonWriter.Formatting = Formatting.Indented;
  20:                  //判断数据读取状态
  21:                  if (dtListProduct.Rows.Count > 0)
  22:                  {
  23:                      Status = true;
  24:                  }
  25:                  jsonWriter.WriteStartObject();
  26:                  jsonWriter.WritePropertyName("Status");
  27:                  jsonWriter.WriteValue(Status);
  28:                  jsonWriter.WritePropertyName("Data");
  29:   
  30:                  jsonWriter.WriteStartArray();
  31:   
  32:                  //先输出第一个元素的类别信息
  33:                  jsonWriter.WriteStartObject();
  34:                  jsonWriter.WritePropertyName("TypeId");
  35:                  jsonWriter.WriteValue(dtListProduct.Rows[0]["TypeId"].ToString());
  36:                  jsonWriter.WritePropertyName("TypeName");
  37:                  jsonWriter.WriteValue(dtListProduct.Rows[0]["TypeName"].ToString());
  38:                  //第一个元素的开始
  39:                  jsonWriter.WritePropertyName("Product");
  40:                  jsonWriter.WriteStartArray();
  41:   
  42:                  //按照类别分组
  43:                  //产品计数(一个分组下的产品,从1开始算起)
  44:                 
  45:                  for (int num = 0,numProduct=1; num < dtListProduct.Rows.Count;num++, numProduct++)
  46:                  {
  47:                     
  48:                      //获取该类别下的分组总个数
  49:                      int Total = Convert.ToInt32(dtListProduct.Rows[num]["total"]);
  50:                      //如果该类别下还存在未输出的产品
  51:                      if (numProduct <= Total)
  52:                      {
  53:                             
  54:   
  55:                              jsonWriter.WriteStartObject();
  56:                              jsonWriter.WritePropertyName("ProductId");
  57:                              jsonWriter.WriteValue(dtListProduct.Rows[num]["Id"].ToString());
  58:                              jsonWriter.WritePropertyName("Name");
  59:                              jsonWriter.WriteValue(dtListProduct.Rows[num]["Name"].ToString ());
  60:                              jsonWriter.WritePropertyName("SimpleName");
  61:                              jsonWriter.WriteValue(dtListProduct.Rows[num]["SimpleName"].ToString());
  62:                              jsonWriter.WritePropertyName("Lsprice");
  63:                              jsonWriter.WriteValue(dtListProduct.Rows[num]["Lsprice"].ToString());
  64:                              jsonWriter.WritePropertyName("Picturepath");
  65:                              jsonWriter.WriteValue(dtListProduct.Rows[num]["Picturepath"].ToString());
  66:                              jsonWriter.WriteEndObject();
  67:   
  68:                          }
  69:                      else{
  70:                          //将该类别的产品计数重置为1
  71:                          numProduct = 1;
  72:                          //这里给上一个类别的产品结束标记
  73:                          
  74:                          jsonWriter.WriteEndArray();
  75:                          jsonWriter.WriteEndObject();
  76:   
  77:                          jsonWriter.WriteStartObject();
  78:                          jsonWriter.WritePropertyName("TypeId");
  79:                          jsonWriter.WriteValue(dtListProduct.Rows[num]["TypeId"].ToString());
  80:                          jsonWriter.WritePropertyName("TypeName");
  81:                          jsonWriter.WriteValue(dtListProduct.Rows[num]["TypeName"].ToString());
  82:                          //如果还存在产品
  83:                          if (num < dtListProduct.Rows.Count)
  84:                          {
  85:                              //下一个元素的开始
  86:                              jsonWriter.WritePropertyName("Product");
  87:                              jsonWriter.WriteStartArray();
  88:   
  89:                          }
  90:                          
  91:                      }
  92:                  }
  93:                  
  94:   
  95:                      jsonWriter.WriteEndArray();
  96:                      jsonWriter.WriteEndObject();
  97:                   
  98:              }
  99:              return json.ToString();
 100:          }

生成的json数据:

这里推荐大家一个工具,就是这个W3Cfuns前端工具,蛮好用的

一步一步asp.net_ajax学习_第7张图片

 

   1:    /// <summary>
   2:          /// 获取大师简介信息
   3:          /// </summary>
   4:          /// <param name="id"></param>
   5:          /// <returns></returns>
   6:          public string GetMasterIntroForJson(string id)
   7:          {
   8:              //加载状态
   9:              bool Status = false;
  10:              int MasterId = Convert.ToInt32(id);
  11:              //获取大师基本信息
  12:              master Info = new masterDAL().Get(MasterId);
  13:   
  14:              //转化为json格式
  15:              StringBuilder json = new StringBuilder();
  16:              StringWriter sw = new StringWriter(json);
  17:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
  18:              {
  19:                  jsonWriter.Formatting = Formatting.Indented;
  20:                  //判断数据读取状态
  21:                  if (Info.Id.HasValue)
  22:                  {
  23:                      Status = true;
  24:                  }
  25:                  jsonWriter.WriteStartObject();
  26:                  jsonWriter.WritePropertyName("Status");
  27:                  jsonWriter.WriteValue(Status);
  28:                  jsonWriter.WritePropertyName("Data");
  29:   
  30:                  jsonWriter.WriteStartArray();
  31:                  jsonWriter.WriteStartObject();
  32:                  jsonWriter.WritePropertyName("Introduction");
  33:                  jsonWriter.WriteValue(Info.Introduction);
  34:                  jsonWriter.WriteEndObject();
  35:                  jsonWriter.WriteEndArray();
  36:   
  37:                  jsonWriter.WriteEndObject();
  38:   
  39:              }
  40:              return json.ToString();
  41:          }
  42:          /// <summary>
  43:          /// 获取大师获奖信息
  44:          /// </summary>
  45:          /// <param name="id"></param>
  46:          /// <returns></returns>
  47:          public string GetMasterRewardForJson(string id)
  48:          { 
  49:           //加载状态
  50:              bool Status = false;
  51:              //获取大师荣誉证书
  52:              IEnumerable<master_cert> masterCertList = new master_certDAL().ListAllById(id);
  53:              int MasterId = Convert.ToInt32(id);
  54:              //获取大师基本信息
  55:              master Info = new masterDAL().Get(MasterId);
  56:   
  57:              //转化为json格式
  58:              StringBuilder json = new StringBuilder();
  59:              StringWriter sw = new StringWriter(json);
  60:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
  61:              {
  62:                  jsonWriter.Formatting = Formatting.Indented;
  63:                  //判断数据读取状态
  64:                  if (Info.Id.HasValue)
  65:                  {
  66:                      Status = true;
  67:                  }
  68:                  jsonWriter.WriteStartObject();
  69:                  jsonWriter.WritePropertyName("Status");
  70:                  jsonWriter.WriteValue(Status);
  71:                  jsonWriter.WritePropertyName("Data");
  72:   
  73:                  jsonWriter.WriteStartArray();
  74:                  jsonWriter.WriteStartObject();
  75:                  jsonWriter.WritePropertyName("Reward");
  76:                  jsonWriter.WriteValue(Info.Reward);
  77:   
  78:                 jsonWriter.WritePropertyName("CertPicList");
  79:                  jsonWriter.WriteStartArray();
  80:                  foreach (master_cert cert in masterCertList)
  81:                  {
  82:                      jsonWriter.WriteStartObject();
  83:                      jsonWriter.WritePropertyName("CertName");
  84:                      jsonWriter.WriteValue(cert.Name);
  85:                      jsonWriter.WritePropertyName("CertPic");
  86:                      jsonWriter.WriteValue(cert.Picpath);
  87:                      jsonWriter.WriteEndObject();
  88:   
  89:                  }
  90:                  jsonWriter.WriteEndArray();
  91:                  jsonWriter.WriteEndObject();
  92:   
  93:   
  94:                  jsonWriter.WriteEndObject();
  95:   
  96:              }
  97:              return json.ToString();
  98:          }
  99:          
 100:          /// <summary>
 101:          /// 获取大师基本信息
 102:          /// </summary>
 103:          /// <param name="id">大师id</param>
 104:          /// <returns></returns>
 105:          public string GetMasterInfoForJson(string id)
 106:          {
 107:              //加载状态
 108:              bool Status = false;
 109:              //获取大师类别信息
 110:              IEnumerable<VMasterType> masterTypeList = new VMasterTypeDAL().ListAllById(id);
 111:              //拼接大师类别信息
 112:              StringBuilder sbTypeName = new StringBuilder();
 113:              foreach (var masterType in masterTypeList)
 114:              {
 115:                  sbTypeName.Append(masterType.TypeName);
 116:   
 117:                  if (masterType != masterTypeList.Last())
 118:                  {
 119:                      sbTypeName.Append(",");
 120:                  }
 121:              }
 122:   
 123:              int MasterId = Convert.ToInt32(id);
 124:              //获取大师基本信息
 125:              master Info = new masterDAL().Get(MasterId);
 126:   
 127:              //转化为json格式
 128:              StringBuilder json = new StringBuilder();
 129:              StringWriter sw = new StringWriter(json);
 130:              using (JsonWriter jsonWriter = new JsonTextWriter(sw))
 131:              {
 132:                  jsonWriter.Formatting = Formatting.Indented;
 133:                  //判断数据读取状态
 134:                  if (Info.Id.HasValue)
 135:                  {
 136:                      Status = true;
 137:                  }
 138:                  jsonWriter.WriteStartObject();
 139:                  jsonWriter.WritePropertyName("Status");
 140:                  jsonWriter.WriteValue(Status);
 141:                  jsonWriter.WritePropertyName("Data");
 142:   
 143:                  jsonWriter.WriteStartArray();
 144:                  jsonWriter.WriteStartObject();
 145:                  jsonWriter.WritePropertyName("Name");
 146:                  jsonWriter.WriteValue(Info.Name);
 147:                  jsonWriter.WritePropertyName("Sex");
 148:                  jsonWriter.WriteValue(Info.Sex == "1" ? "男" : "女");
 149:                  jsonWriter.WritePropertyName("Birthday");
 150:                  jsonWriter.WriteValue(Info.BirthDay.Value.ToShortDateString());
 151:                  jsonWriter.WritePropertyName("PicturePath");
 152:                  jsonWriter.WriteValue(Info.Picturepath);
 153:                  jsonWriter.WritePropertyName("TypeName");
 154:                  jsonWriter.WriteValue(sbTypeName.ToString());
 155:                  jsonWriter.WriteEndObject();
 156:                  jsonWriter.WriteEndArray();
 157:   
 158:                  jsonWriter.WriteEndObject();
 159:   
 160:              }
 161:              return json.ToString();
 162:          }
 
这样这次的任务就完成了,总体感觉蛮不错的,效果很好,就是那个json数据拼接拼了好久,纠结了好久.
接下来,尽快把这个项目完整的做完,静态页面管理,大师空间,企业空间,第三方支付平台,等等,然后步入asp.net mvc学习.....哈哈!
 
 
 

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