欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net新闻列表生成静态页之批量和单页生成

程序员文章站 2023-11-12 15:42:34
大家都知道,生成静态页的方法有两种,第一种是使用c#在后台硬编码,第二种是读取模板文件,使用字符串代替。总体来讲第一种方法代码量比较大,维护起来有点困难。生成静态页的目的是...

大家都知道,生成静态页的方法有两种,第一种是使用c#在后台硬编码,第二种是读取模板文件,使用字符串代替。总体来讲第一种方法代码量比较大,维护起来有点困难。生成静态页的目的是为了提高用户体验度,加快访问速度。

使用静态页面还有如下好处:
1、 安全:使用静态页面,用户访问的使没有任何操作功能的html页面,可以说从安全性方面大大提高了程序及服务器的安全。

2、 快速:用户访问的是提前生成好的静态页面,使用户对页面的请求瓶颈只受io的限制而不会有其他方面的影响。

3、 降低服务器,数据库负载:因为用户访问的是静态页,对承载静态页的服务器配置要求降低了许多,同时,不会因为过大的访问量,造成数据库服务器负载过重等问题。

下面分享asp.net新闻列表生成静态页之批量和单页生成。前期准备,需要新建一个文件夹。。前台展示:/new/default.aspx  这个页面放的就是动态的新闻列表数据。

先看下图:

asp.net新闻列表生成静态页之批量和单页生成

 asp.net新闻列表生成静态页之批量和单页生成

不多说了上代码

这里要说明一下,我用的aspnetpager分页控件,需要设置一下

<webdiyer:aspnetpager id="aspnetpager1" runat="server" firstpagetext="首页"
 lastpagetext="末页" nextpagetext="下一页" numericbuttoncount="10" 
 onload="aspnetpager1_load" onpagechanged="aspnetpager1_pagechanged1"
 pagesize="13" prevpagetext="上一页" font-bold="false" font-size="13px"
 cssclass="badoo" urlpaging="true" currentpagebuttonposition="center" 
 pagingbuttonspacing="5px" enableurlrewriting="true" 
 urlrewritepattern="news_{0}.html" showmorebuttons="false" 
 showpageindexbox="never" >
  </webdiyer:aspnetpager>

需要设置三个地方:

urlpaging="true" 设置启用url来传递分页信息  enableurlrewriting="true" 启用url重写   urlrewritepattern="news_{0}.html" 设置分页url重写格式

static.ashx页面代码

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.text;
using system.io;
using system.net;
using system.data;
namespace web.admin.ashx
{
 /// <summary>
 /// static 生成静态页
 /// </summary>
 public class static : ihttphandler
 {
  public void processrequest(httpcontext context)
  {
   string url = context.request["geturl"];
   string path = context.request["getpath"];
   string id = context.request["id"];
   string act = context.request["act"];
   string page = context.request["pages"];
   string pagecount = context.request["pagecouts"];
   string table = context.request["table"];
   string str = "";
   if (act == "0")
   {
    //生成当前选中项
    string ids = id.substring(0, (id.length - 1));
    string[] s_id = ids.split(',');
    for (int i = 0; i < s_id.length; i++)
    {
     string path2 = context.server.mappath("../../" + path + s_id[i] + ".html");
     str = createhtml("http://localhost:4216/" + url + s_id[i], path2); //这里必须是拼接的绝对路径
     string urls = "http://localhost:4216/" + path + s_id[i] + ".html"; //这里必须是拼接的绝对路径
     string sql = string.format("update {0} set static =1,url='{1}' where id={2}", table, urls, s_id[i]);
     if (new dbtool.db().runsqlgetrowcount(sql) > 0)
     {
     }
    }
    context.response.write(str);
    context.response.end();
   }
   if (act == "1")
   {
    //生成当前页列表
    string path2 = context.server.mappath("../../" + path + page + ".html");
    str = createhtml("http://localhost:4216/" + url + page, path2);
    context.response.write(str);
    context.response.end();
   }
   if (act == "2")
   {
    //生成全部列表
    int count = convert.toint32(pagecount);
    for (int i = 1; i <= count; i++)
    {
     string path2 = context.server.mappath("../../" + path + i + ".html");
     str = createhtml("http://localhost:4216/" + url + i, path2);
    }
    context.response.write(str);
    context.response.end();
   }
   if (act == "3")
   {
    //生成全部项
    string sqlsel =string.format("select id from {0}",table);
    datatable dt = new dbtool.db().runsqlgetdatatable(sqlsel);
    if (dt.rows.count > 0)
    {
     string idall = "";
     for (int i = 0; i < dt.rows.count; i++)
     {
      idall += dt.rows[i]["id"].tostring()+",";
     }
     string ids = idall.substring(0, (idall.length - 1));
     string[] s_id = ids.split(',');
     for (int ii = 0; ii < s_id.length; ii++)
     {
      string path2 = context.server.mappath("../../" + path + s_id[ii] + ".html");
      str = createhtml("http://localhost:4216/" + url + s_id[ii], path2);
      string urls = "http://localhost:4216/" + path + s_id[ii] + ".html";
      string sql = string.format("update {0} set static =1,url='{1}' where id={2}", table, urls, s_id[ii]);
      if (new dbtool.db().runsqlgetrowcount(sql) > 0)
      {
      }
     }
     context.response.write(str);
     context.response.end();
    }
   }
  }
  public string createhtml(string strurl, string path)
  {
   string str = "";
   streamreader sr;
   streamwriter sw = null;
   try
   {
    webrequest httpwebrequest = webrequest.create(strurl);
    webresponse httpwebresponse = httpwebrequest.getresponse();
    sr = new streamreader(httpwebresponse.getresponsestream(), system.text.encoding.getencoding("utf-8"));
    string strhtml = sr.readtoend();
    sw = new streamwriter(path, false, system.text.encoding.getencoding("utf-8"));
    sw.writeline(strhtml);
    sw.flush();
    sw.close();
    str = "生成成功!";
   }
   catch (exception ex)
   {
    str = "生成失败,失败原因" + ex.message+"。";
   }
   return str;
  }
  public bool isreusable
  {
   get
   {
    return false;
   }
  }
 }
}

后台生成前台代码

  

<div>
  <table border="0" cellpadding="0" cellspacing="0" class="list_table1">
 <tr>
 <td width="13%"><input type="text" runat="server" id="text_word" class="text lh20" placeholder="请输入关键字"/></td>
 <td width="5%">
  <asp:button id="button1" runat="server" text="搜索" cssclass="suborange" onclick="button1_click" />
 </td>
  <td width="82%"> <a href="list.aspx" class="subgreen">查看全部</a></td>
 </tr>
</table>
 <table width="100%" border="0" cellpadding="0" cellspacing="0" class="list_table"><tr>
  <th width="30"> </th>
  <th width="60" data-field="id" data-url="newslist.aspx" >id<img id="lab_id" src="images/a2.png" /></th>
  <th width="200" data-field="name" data-url="newslist.aspx" >名称<img id="lab_name" src="images/a2.png" /></th>
  <th width="200" data-field="dir" data-url="newslist.aspx">地址<img id="lab_dir" src="images/a2.png" /></th>
  <th width="150" data-field="static" data-url="newslist.aspx">静态化<img id="lab_static" src="images/a2.png" /></th>
  <th>操作</th>
</tr>
  <asp:repeater id="r1" runat="server" onitemdatabound="r1_itemdatabound" ><itemtemplate>
   <tr class="tr" id='tr_<%#eval("id")%>'>
<td class="td_center"><label id='labe_<%#eval("id")%>'><asp:checkbox id="chkitem" runat="server" tooltip='<%#eval("id")%>'></asp:checkbox></label><input type="hidden" id="text_id" runat="server" value='<%#eval("id")%>' /></td>
     <td class="td_center"> <%#eval("id") %></td>
     <td class="td_center"> <%#eval("name") %></td>
    <td class="td_center">
<a href="javascript:;" class="a_1" data-id='<%#eval("id") %>' data-field='dir' data-table='hotelinfo' data-url="newslist.aspx">
     <%#eval("dir") %></a></td>
    <td class="td_center"> 
     <asp:label id="lab_state" runat="server" text='<%#eval("static") %>'></asp:label>
    </td>
    <td class="td_center">
     <a href="<%#eval("url") %>" class="a_2" target="_blank">查看</a>
    <%--data-table data-fild 为复制数据的表明和字段--%>
<span data-id="<%#eval("id") %>" class="more" data-table="users" data-fild="name,password" data-url="list.aspx" data-itemid="<%# container.itemindex + 1%>">更多操作</span>
      </td></tr>
</itemtemplate>
</asp:repeater></table>
  <div id="div_none" runat="server" visible="false" style="width: 300px; margin: 20px auto">很抱歉,暂无数据。</div>
  <div id="button" class="mt10">
   <input type="button" name="button" class="btn btn82 btn_del" value="删除" onclick="dels('hotelinfo', 'newslist.aspx')" />
   <input type="button" name="button" class="btn btn82 btn_checked" value="全选" onclick="quanxuan()" />
   <input type="button" name="button" class="btn btn82 btn_nochecked" value="取消" onclick="fanxuan()" />
    <asp:button id="button3" runat="server" text="添加" cssclass="btn btn82 btn_add" postbackurl="addarticle.aspx" />
  </div>
  <webdiyer:aspnetpager id="aspnetpager1" runat="server" firstpagetext="首页" lastpagetext="末页" nextpagetext="下一页" numericbuttoncount="10" onload="aspnetpager1_load" onpagechanged="aspnetpager1_pagechanged1" pagesize="13" prevpagetext="上一页" font-bold="false" font-size="13px" cssclass="badoo" urlrewritepattern="" urlpaging="true" currentpagebuttonposition="center" pagingbuttonspacing="5px" showfirstlast="false" showmorebuttons="false" showpageindexbox="never" >
  </webdiyer:aspnetpager>
  <div class="div_count">
   <asp:label id="lab_num" runat="server" text=""></asp:label>
  </div>
  <div class="div_both"></div>
   <input type="hidden" id="text_delid" runat="server" />
  <input type="hidden" id="text_page" value='<%=page() %>' />
  <input type="hidden" id="text_pagecount" runat="server" />
  <br />

生成静态列表:

<input type="button" class="suborange static" value="生成当前页列表" data-href="newslist.aspx" data-act="1" data-url="news/default.aspx?page=" data-path="news/news_" />

<input type="button" class="subcyan static" value="生成全部列表" data-href="newslist.aspx" data-act="2" data-url="news/default.aspx?page=" data-path="news/news_" />
<a href="../news/news_1.html" class="subgreen" target="_blank">查看新闻列表</a>
  

生成静态页:

 <input type="button" class="submit static" value="生成当前选中项" data-href="newslist.aspx" data-act="0" data-url="newsel/default.aspx?id=" data-path="newsel/newsel_" data-table="hotelinfo"/>
<%-- <input type="button" class="subgreen static" value="生成全部项" data-href="newslist.aspx" data-act="3" data-table="hotelinfo" data-url="newsel/default.aspx?id=" data-path="newsel/newsel_" />--%>

  <div id="divdialog"></div>

  <div id="loading"><div id="message"></div></div>
  </div>

cs代码

我用的是存储过程加载数据,存储过程具体使用方法请看另一篇文章

using system;
using system.web;
using system.data.sqlclient;
using system.data;
using system.collections.generic;
using system.web.script.serialization;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.text;
using system.io;
using system.net;
namespace web.admin
{
 public partial class newslist : system.web.ui.page
 {
  protected void page_load(object sender, eventargs e)
  {
   if (!ispostback)
   {
    httpcookie hcname = request.cookies["backname"];
    if (hcname != null)
    {
     string s = request.url.tostring().substring(request.url.tostring().lastindexof('/') + 1);
     if (s.indexof("?") > -1) s = s.substring(0, s.indexof("?"));
     httpcookie hc1 = new httpcookie("backurl", s);
     hc1.expires = datetime.now.addminutes(120);
     response.cookies.add(hc1);
     string title = this.page.title.tostring();
     httpcookie hc2 = new httpcookie("backtitle", server.urlencode(title));
     hc2.expires = datetime.now.addminutes(120);
     response.cookies.add(hc2);
     bind();
    }
    else
    {
     this.page.registerstartupscript("aaa", "<script>tuichu();</script>");
    }
   }
  }
  public void bind()
  {
   sqlparameter[] parms = new sqlparameter[] { 
  new sqlparameter("@feilds",sqldbtype.nvarchar,1000),
  new sqlparameter("@page_index",sqldbtype.int,10),
  new sqlparameter("@page_size",sqldbtype.int,10),
  new sqlparameter("@ordertype",sqldbtype.int,2),
  new sqlparameter("@andwhere",sqldbtype.varchar,1000),
  new sqlparameter("@orderfeild",sqldbtype.varchar,100),
  new sqlparameter("@tablename",sqldbtype.varchar,100)
  };
   parms[0].value = "id,name,dir,static,url";//获取所有的字段
   parms[1].value = page();//当前页面索引
   parms[2].value = 10;//页面大小
   parms[3].value = paixu();//升序排列
   parms[4].value = "(name like '%" + keyword() + "%')";//条件语句
   parms[5].value = paixuziduan();//排序字段
   parms[6].value = "hotelinfo";//表名
   datatable dt = new datatable();
   using (sqldatareader sdr = yoodor.dal.sqlhelper.executereader(commandtype.storedprocedure, "pagination", parms))
   {
    dt.load(sdr);
    r1.datasource = dt;
    r1.databind();
   }

   if (keyword() != null && keyword() != "none")
   {
    text_word.value = keyword();
   }
  }
  public int page()
  {
   int pagenumber = request.querystring["page"] != null ? convert.toint32(request.querystring["page"].tostring()) : 1;
   return pagenumber;
  }
  public string keyword()
  {
   string key = request.querystring["keyword"] != null ? request.querystring["keyword"].tostring() : "";
   return key;
  }
  public string type()
  {
   string key = request.querystring["type"] != null ? request.querystring["type"].tostring() : "";
   return key;
  }
  public string paixuziduan()
  {
   string str = "";
   string s = request.querystring["field"];
   if (s != null)
   {
    str = s;
   }
   else
   {
    str = "id";
   }
   return str;
  }
  public int paixu()
  {
   string asc = request.querystring["asc"];
   if (asc != null)
   {
    if (asc == "desc")
    {
     return 0;
    }
    else
    {
     return 1;
    }
   }
   else
   {
    return 1;
   }
  }
  //分页事件
  protected void aspnetpager1_pagechanged1(object sender, eventargs e)
  {
   bind();
  }
  protected void aspnetpager1_load(object sender, eventargs e)
  {
   string count = new bll.f_article().selectallnum(keyword(), type());
   aspnetpager1.recordcount = convert.toint32(count);
   lab_num.text = "共<span class='count'>" + count + "</span>条记录。";
   text_pagecount.value = aspnetpager1.pagecount.tostring();   
  }
  protected void r1_itemdatabound(object sender, repeateritemeventargs e)
  {
   if (e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem)
   {
    checkbox ch = (checkbox)e.item.findcontrol("chkitem");
    htmlinputhidden tid = (htmlinputhidden)e.item.findcontrol("text_id");
    ch.attributes.add("onclick", "checks(" + tid.value + ")");
    label state = (label)e.item.findcontrol("lab_state");
    if (state.text == "0")
    {
     state.text = "未静态";
     state.forecolor = system.drawing.color.red;
    }
    else {
     state.text = "已静态";
    }
   }
  }
  //搜索
  protected void button1_click(object sender, eventargs e)
  {
   string keyword = text_word.value.trim();
   response.redirect("list.aspx?keyword=" + keyword, false);
  }
 }
}

glob.js代码

$(function () {
 //创建弹出提示框
 var divdialog = '<div id="divdialog"></div><div id="divsuredialog"></div>';
 $(document.body).append(divdialog);
 //表格行,鼠标放上去变色
 $(".tr:odd").css("background", "#fffcea");
 $(".tr:odd").each(function () {
  $(this).hover(function () {
   $(this).css("background-color", "#f5f8f9");
  }, function () {
   $(this).css("background-color", "#fffcea");
  });
 });
 $(".tr:even").each(function () {
  $(this).hover(function () {
   $(this).css("background-color", "#f5f8f9");
  }, function () {
   $(this).css("background-color", "#fff");
  });
 });
 //生成静态页
 $(".static").click(function () {
  var url = $(this).attr("data-url");
  var path = $(this).attr("data-path");
  var href = $(this).attr("data-href");
  var tablename = $(this).attr("data-table");
  var actid = $(this).attr("data-act"); //0 表示生成当前选中项
  var ids = $("#text_delid").val();
  var page = $("#text_page").val();
  var pagecount = $("#text_pagecount").val();
  if (actid == 0) {
   if (ids == "") {
    dialog(1, '请先选择!');
    return false;
   }
  }
   $.ajax({
    url: "ashx/static.ashx",
    data: { "geturl": url, "getpath": path, "act": actid, "id": ids, "pages": page, "pagecouts": pagecount, "table": tablename },
    type: "post",
    beforesend: function (data) {
     doprogress(href, "生成成功!");
    },
    success: function (data) {
     doprogress(href, data);
    }
   })
  
 })
});
var progress_id = "loading";
function setprogress(progress) {
 if (progress) {
  $("#" + progress_id + " > div").css({ "width": string(progress) + "%", "background": "#f4a830" }); //控制#loading div宽度 
  $("#" + progress_id + " > div").html(string(progress) + "%"); //显示百分比 
 }
}
var i = 0;
function doprogress(href, msg) {
 $("#loading").show();
 if (i > 100) {
  $("#message").html(msg).fadein("fast");//加载完毕提示 
  // window.location.href = href;
  $("#loading").hide();
  dialog(0, msg, href, 1000);
  return;
 }
 if (i <= 100) {
  settimeout("doprogress('"+href+"','"+msg+"')", 1);
  setprogress(i);
  i++;
 }
}
function checks(id) {
var spid = "";
spid += id + ",";
var aa = $("#text_delid").val();
if ($("#labe_" + id + " input").attr("checked")) {

 // $("#tr_" + id).css("background","#000");
 $("#text_delid").val(aa + spid);
 return false;
}
else {
 //$("#tr_" + id).removeclass("hover1");

 if (aa.indexof(id) > -1) {
  var b = aa.replace(id + ",", "");
  $("#text_delid").val(b);
 }
}

}
//删除确认框
function dels(tablename,url) {
var id = $("#text_delid").val();
if (id == "") {
dialog(1, '请先选择!');
return false;}
else {$("#divdialog").hide();
suredialog(id, "您确定要删除吗?删除之后信息将不再显示!",tablename,url);
return false;}}
function newdels() {
 var tablename = $("#text_table").val();
 var url = "type.aspx?table=" + tablename;
 var id = $("#text_delid").val();
 if (id == "") {
  dialog(1, '请先选择!');
  return false;
 }
 else {
  $("#divdialog").hide();
  suredialog(id, "您确定要删除吗?删除之后信息将不再显示!", tablename, url);
  return false;
 }
}
//全选反选
function quanxuan() {
$(':checkbox').each(function () {
$(this).attr("checked", true);
var spid = "";
var id = $(this).parent('span').attr("title");
spid += id + ",";
var aa = $("#text_delid").val();
$("#text_delid").val(aa + spid);
})}
function fanxuan() {
$(':checkbox').each(function () {
$(this).attr("checked", false);
$("#text_delid").val('');
})}
//删除信息
function deleteinfor(ids, table,url) {
$("#divsuredialog").hide();
var page = $('#text_page').val();
$.post("ashx/delete.ashx?id=" + ids + "&table=" + table + "", null, function (data) {
 if (data == 1) {
  if (url.indexof("type.aspx") > -1) {
   dialog(0, '删除成功', url, 1000);
  }
  else {
   dialog(0, '删除成功', url + '?page=' + page + '', 1000);
  }
 }
else { dialog(2, '删除失败', url + '?page=' + page + '', 1000);}
});
}
var dlog;
var pp = false;
kindeditor.ready(function (k) {
 k('.a_1').click(function () {
$("#divsuredialog").hide();
$("#divdialog").hide();
var id = $(this).attr("data-id");
var value1 = $(this).attr("data-value");
var value = "";
var html = "";
if ($(this).html().indexof('通过')>-1) {
 value = value1;
 html="修改审核状态(点击确定即可)"
}
else {
 value = $(this).html();
 html = "修改信息";
}

var field = $(this).attr("data-field");
var table = $(this).attr("data-table");
var url = $(this).attr("data-url");

dlog = k.dialog({
width: 260,
title: html,
body: "<div style='margin:10px; height:130px'><table width='100%' border='0'><tr><td style='text-align:center; height:50px; '><input type='text' id='text_updatevalue' value=" + value + " class='text lh20' /> </td></tr><tr><td style='text-align:center;height:50px;'><input type='button' onclick=upateinfor('" + id + "','" + field + "','" + table + "','" + url + "') class='subgreen' value='确定' />     <input type='button' onclick='closedlog()' class='suborange' value='取消' /></td></tr></table></div>",
closebtn: { name: '关闭', click: function (e) { dlog.remove(); } }
});
 });

 k('#newsadd').click(function () {
  $("#divsuredialog").hide();
  $("#divdialog").hide();
  dlog = k.dialog({
   width: 260,
   title: '新增分类',
   body: "<div style='margin:10px; height:130px'><table width='100%' border='0'><tr><td style='text-align:center; height:50px; '><input type='text' id='text_typevalue' class='input-text lh20' /> </td></tr><tr><td style='text-align:center;height:50px;'><input type='button' onclick=inserttype() class='subgreen' value='确定' />     <input type='button' onclick='closedlog()' class='suborange' value='取消' /></td></tr></table></div>",
   closebtn: { name: '关闭', click: function (e) { dlog.remove(); } }
  });
 });


});
//修改信息
function upateinfor(ids, fieldname, tablename, url) {
var page = $('#text_page').val();
var value = $("#text_updatevalue").val();
$.post("ashx/update.ashx?id=" + ids + "&table=" + tablename + "&field=" + fieldname + "&value=" + escape(value) + "", null, function (data) {
if (data == 1) {
 closedlog();
 if (url.indexof("type.aspx") > -1) {
  dialog(0, '修改成功', url, 1000);
 }
 else {
  dialog(0, '修改成功', url + '?page=' + page + '', 1000);
 }
}
else { closedlog(); dialog(2, '修改失败', url+'?page=' + page + '', 1000); }
});
}
//修改信息 带值
function upateinforss(ids, value, fieldname, tablename, url) {
 var page = $('#text_page').val();
 $.post("ashx/update.ashx?id=" + ids + "&table=" + tablename + "&field=" + fieldname + "&value=" + escape(value) + "", null, function (data) {
  if (data == 1) {
   $("#div_tip").hide();
   if (url.indexof("type.aspx") > -1)
   {
    dialog(0, '修改成功', url , 1000);
   }
   else {
    dialog(0, '修改成功', url + '?page=' + page + '', 1000);
   }
  }
  else { closedlog(); dialog(2, '修改失败', url + '?page=' + page + '', 1000); }
 });
}
//增加分类
function inserttype(){
 var value = $("#text_typevalue").val();
 var table = $("#text_table").val();
 var url = "type.aspx?table="+table;
 var page = $('#text_page').val();
 $.post("ashx/insert.ashx?table="+table+"&value=" + escape(value) + "", null, function (data) {
  if (data == 1) {
   closedlog();
   dialog(0, '添加成功', url, 1000);
  }
  else { closedlog(); dialog(2, '添加失败', url , 1000); }
 });
}
function closedlog() { dlog.remove(); }
//弹出删除 确认对话框
function suredialog(id, msg, tablename,url) {
 var html = "<div class='sure_title'>系统提示<a href='javascript:;' onclick='closesurediv()'></a></div><div class='sure_content'></div><div class='sure_btn'><input type='hidden' id='text_deleid' /><input type='button' onclick=deleteinfor('" + id + "','" + tablename + "','"+url+"') value='确定' class='subgreen' />    <input type='button' onclick='closesurediv()' value='取消' class='suborange' /></div>";
 $("#divsuredialog").show();
 $("#divsuredialog").html(html);
 $(".sure_content").html(msg);
}

以上内容是asp.net新闻列表生成静态页之批量和单页生成的全部内容,还有生成文章静态页,在这里我要提醒大家生成文章的静态页的方法给这个是不一样的,请继续关注本网站,我会持续更新的。谢谢大家阅读我的作品。