动态生成JS 实现 .NET 网站广告管理
一般的网站,其中的广告都需要定期更换和管理。对于广告的存储,一般选用的数据源是数据库或者XML。而对于广告的显示,一般有两种方法:
一是使用AdRotator广告组件。这样很容易实现,通过封装AdRotator控件,在需要显示广告的页面放置自定义控件并设置广告关键词:
2 | AdControl.ascx: |
2 3 | <%@ Control Language= "C#" AutoEventWireup= "true" CodeFile= "AdControl.ascx.cs" Inherits= "Controls_AdControl" %> <asp:AdRotator ID= "Ror" runat= "server" /> |
2 | AdControl.ascx.cs: |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | public partial class Controls_AdControl : System.Web.UI.UserControl { private string keyWord; private string KeyWord { get { return keyWord; } set { keyWord = value; } } private int height; public int Height { get { return height; } set { height = value; } } private int width; public int Width { get { return width; } set { width = value; } } private string city; public string City { get { return city; } set { city = value; } } //OnLoadComplete protected void Page_Load( object sender, EventArgs e) { //if (!IsPostBack) //{ //} } public void KeywordBind( string key){ keyWord = key; if (height > 0) Ror.Height = height; if (width > 0) Ror.Width = width; city = Profile.city; if ( string .IsNullOrEmpty(city)) city = "武汉" ; Ror.KeywordFilter = keyWord; Ror.DataSource = AdDA.GetAdList(keyWord, city); Ror.DataBind(); } |
缺点:每显示一个广告,就需要数据库有一次连接;那一个页面过多的广告,对数据库的消耗太大;
第二种方式,使用JS来管理广告,具体方法:
广告信息存于数据库中(图片地址,alter信息等),使用C#读写文件生成ad.js:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | using (StreamWriter sw = new StreamWriter(url)) //"d:\\DJS\\ad.js" { DataTable dt = AdDA.EnumAdList(); string src, keyword, alter, link; sw.WriteLine( "$(document).ready(function(){" ); foreach (DataRow dr in dt.Rows) { src = dr[ "ImageUrl" ].ToString(); keyword = dr[ "keyword" ].ToString(); alter = dr[ "AlternateText" ].ToString(); link = dr[ "NavigateUrl" ].ToString(); sw.WriteLine( "$('#" +keyword+ "i').attr({" ); sw.WriteLine( " 'src': '" + src + "', 'alt': '" + alter + "'" ); sw.WriteLine( "});" ); sw.WriteLine( "$('#" + keyword + "a').attr({" ); sw.WriteLine( "'href':'" +link+ "'" ); sw.WriteLine( "});" ); } sw.WriteLine( "});" ); } |
在页面中包含该JS:
2 3 | <script type= "text/javascript" src= "js/jquery.js" ></script> <script type= "text/javascript" src= "js/ad.js" ></script> |
2 | <font face= "华文中宋" size= "2" >在需要显示广告的位置加上相应的标签:</font> |
2 | <a id= "iR1a" ><img id= "iR1i" width= "165" height= "120" /></a> |
如此,在更新广告信息后只需要重新生成ad.js即可实现网站的广告更新。
OVER
2 | |
分类:
Web 开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述