asp.net新闻列表生成静态页之批量和单页生成
大家都知道,生成静态页的方法有两种,第一种是使用C#在后台硬编码,第二种是读取模板文件,使用字符串代替。总体来讲第一种方法代码量比较大,维护起来有点困难。生成静态页的目的是为了提高用户体验度,加快访问速度。
使用静态页面还有如下好处:
1、 安全:使用静态页面,用户访问的使没有任何操作功能的html页面,可以说从安全性方面大大提高了程序及服务器的安全。
2、 快速:用户访问的是提前生成好的静态页面,使用户对页面的请求瓶颈只受IO的限制而不会有其他方面的影响。
3、 降低服务器,数据库负载:因为用户访问的是静态页,对承载静态页的服务器配置要求降低了许多,同时,不会因为过大的访问量,造成数据库服务器负载过重等问题。
下面分享asp.net新闻列表生成静态页之批量和单页生成。前期准备,需要新建一个文件夹。。前台展示:/new/default.aspx 这个页面放的就是动态的新闻列表数据。
先看下图:
不多说了上代码
这里要说明一下,我用的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代码
我用的是存储过程加载数据,存储过程具体使用方法请看另一篇文章http://www.jb51.net/article/42950.htm
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新闻列表生成静态页之批量和单页生成的全部内容,还有生成文章静态页,在这里我要提醒大家生成文章的静态页的方法给这个是不一样的,请继续关注本网站,我会持续更新的。谢谢大家阅读我的作品。