您的位置:首页 > 运维架构 > 网站架构

动态生成JS 实现 .NET 网站广告管理

2010-11-13 23:16 429 查看
一般的网站,其中的广告都需要定期更换和管理。对于广告的存储,一般选用的数据源是数据库或者XML。而对于广告的显示,一般有两种方法:

一是使用AdRotator广告组件。这样很容易实现,通过封装AdRotator控件,在需要显示广告的页面放置自定义控件并设置广告关键词:

AdControl.ascx:<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="AdControl.ascx.cs"Inherits="Controls_AdControl"%> <asp:AdRotatorID="Ror"runat="server"/>AdControl.ascx.cs:publicpartialclassControls_AdControl:System.Web.UI.UserControl { privatestringkeyWord; privatestringKeyWord { get{returnkeyWord;} set{keyWord=value;} } privateintheight; publicintHeight { get{returnheight;} set{height=value;} } privateintwidth; publicintWidth { get{returnwidth;} set{width=value;} } privatestringcity; publicstringCity { get{returncity;} set{city=value;} } //OnLoadComplete protectedvoidPage_Load(objectsender,EventArgse) { //if(!IsPostBack) //{ //} } publicvoidKeywordBind(stringkey){ 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:

using(StreamWritersw=newStreamWriter(url))//"d:\\DJS\\ad.js" { DataTabledt=AdDA.EnumAdList(); stringsrc,keyword,alter,link; sw.WriteLine("$(document).ready(function(){"); foreach(DataRowdrindt.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:

<scripttype="text/javascript"src="js/jquery.js"></script> <scripttype="text/javascript"src="js/ad.js"></script>在需要显示广告的位置加上相应的标签:<aid="iR1a"><imgid="iR1i"width="165"height="120"/></a>
如此,在更新广告信息后只需要重新生成ad.js即可实现网站的广告更新。

OVER

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: