asp.net动态从数据库中加载产品数据显示在网页上(用于网页产品信息展示滚动显示)
在前台上写上两个div层用来展示的
要实现的前台效果:
<div id="container">
<div id="message" runat="server">
<ul>
<li><a href="#" target="_self" title="Produce"><img src="Img/PIC/5712A.jpg" alt="产品" /></a></li>
<li><a href="#" target="_self" title="Produce"><img src="Img/PIC/5712B.jpg" alt="产品" /></a></li>
</ul>
<ul>
<li><a href="#" target="_self" title="Produce"><img src="Img/PIC/5712C.jpg" alt="产品" /></a></li>
<li><a href="#" target="_self" title="Produce"><img src="Img/PIC/5712E.jpg" alt="产品" /></a></li>
</ul>
</div>
</div>
..............蓝色的部分就是要求后台加上的,这样网页才能方便......................................................................
<div id="container">
<div id="message" runat="server"></div>
</div>
只有 div 要用ID而不能是class属性 最后加上runat=“server”后台才能调用div层
后台代码如下:
定义一个结构体:listParam
public struct listParam
{
public string url
{
get;
set;
}
public string src
{
get;
set;
}
public string title
{
get;
set;
}
}
/// <summary>
/// 读取数据库产品数据
/// </summary>
/// <returns></returns>
public System.Collections.Generic.List<listParam> GetList()
{
List<listParam> result = new List<listParam>();
listParam lp;
try{
string dataPart = ConfigurationManager.AppSettings["ConnStr"];
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath(dataPart));
con.Open();
string sql = "select * from tbProducts";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataReader Myreader = cmd.ExecuteReader();
while (Myreader.Read())
{
lp=new listParam();
lp.url = "FlyWay_Produce_More.aspx?ID=" + Myreader["ModelNO"].ToString();//点击产品转到产品详细信息介绍页面
lp.src = Myreader["Picture1"].ToString();
lp.title = Myreader["Title"].ToString();
result.Add(lp);
}
Myreader.Close();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return result;
}
/// <summary>
/// 在后台往网页上写html代码
/// </summary>
protected void MarkLink()
{
string templelink="<ul><li><a href='{0}' target='_self' title='{1}'><img src='{2}' alt='产品' /></a></li><li><a href='{3}' target='_self' title='{4}'><img src='{5}' alt='产品' /></a></li></ul>";
string result1 = "";
System.Collections.Generic.List<listParam> list = GetList();
int total = list.Count > 4 ? 4 : list.Count;//只显示4个产品,多了的话,网页载入时间长
for (int i = 1; i < total; i++)
{
result1 += string.Format(templelink, list[i - 1].url, list[i - 1].title, list[i - 1].src, list[i].url, list[i].title, list[i].src);
}
//foreach (listParam lp in list)//也可以全部读取显示
//{
// result += string.Format(templelink, lp.url, lp.title, lp.src, lp.url, lp.title, lp.src);
//}
message.InnerHtml = result1;
}
然后再页面载入的时候读取显示
protected void Page_Load(object sender, EventArgs e)
{
MarkLink();
}
浙公网安备 33010602011771号