我有一个带图片库的网站。我想动态地将图片添加到图库。我有这段代码:
string[] files = Directory.GetFiles(Server.MapPath(@"images\gallery\projects"));
string temp = files[0];
for (int i = 1; i < files.Length; i++)
{
HyperLink hp = new HyperLink();
hp.ImageUrl = "images/gallery/projects/" + Path.GetFileName(files[i]);
hp.NavigateUrl = "images/gallery/projects/" + Path.GetFileName(temp);
Panel1.Controls.Add(hp);
temp = files[i];
}
用图片迭代文件夹并生成链接标签但不是我需要的。我正在尝试生成此标记:
<a href="images/gallery/picture_fullsize.jpg"
title="Caption for picture goes here">
<img src="images/gallery/picture_thumbnail.jpg"/>
</a>
非常感谢任何指针或解决方案。
答案 0 :(得分:2)
我建议您使用模板控件(如转发器)来解决此问题。看起来你已经设置好了,因为你正在使用一个可以作为绑定数据源的列表。应尽可能避免动态创建html。
在此处查看更多信息:
http://msdn.microsoft.com/en-us/library/zzx23804(v=vs.85).aspx
答案 1 :(得分:2)
您现有的方法很棒,强类型,并且比自己创建链接更不容易出错。
如果要为标记添加标题,可以使用Attributes.Add
方法。
var hp = new HyperLink();
hp.ImageUrl = "images/gallery/projects/" + Path.GetFileName(files[i]);
hp.NavigateUrl = "images/gallery/projects/" + Path.GetFileName(temp);
hp.Attributes.Add("title", "Caption for picture goes here");
Panel1.Controls.Add(hp);
答案 2 :(得分:1)
使用HtmlTextWriter。它允许您创建漂亮干净的HTML,并可以轻松地执行您想要的嵌套标记。所以你的代码看起来像这样:
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) //Always enclose in 'using' for cleaner code
for (int i = 1; i < files.Length; i++)
{
//Write the starting 'a' tag
writer.AddAttribute(HtmlTextWriterAttribute.Href, "images/gallery/projects/" + Path.GetFileName(temp));
writer.RenderBeginTag(HtmlTextWriterTag.A);
//Write the starting 'img' tag
writer.AddAttribute(HtmlTextWriterAttribute.Src, "images/gallery/projects/" + Path.GetFileName(files[i]));
writer.RenderBeginTag(HtmlTextWriterTag.Img);
//Close the 'img' tag
writer.RenderEndTag();
//Close the 'a' tag
writer.RenderEndTag();
}
var generatedHtml = stringWriter.ToString(); //The final HTML