在我正在设计的网站中,我需要显示我使用 asp:FileUpload 控件上传的图像。因此,在上传后,我使用字符串生成器添加 div、img 和 textarea,然后将其加载到我已经创建的面板中。那么使用Stringbuilder加载内部HTML更好还是使用HtmlgenericControls添加图像和textarea等控件更好。我正在使用 C#。我目前的编码方式如下:
前端:
<form id="form1" runat="server">
<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
<asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
<asp:Button runat="server" ID="uploadedFile" style="position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
<asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
</asp:Panel>
</div>
</form>
后端如下:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
int tid = 0;
string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
{
HtmlGenericControl d = new HtmlGenericControl("div");
Button btnsave = new Button();
btnsave.Text = "Save";
sb.Append("<div class=" + "\"savback\"" + ">");
sb.Append("<div class=" + "\"head\"" + ">Write Description</div>");
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
id += 1;
tid = tid + 1;
string textid = "txt" + tid;
filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
uploadedFile.SaveAs(filepath);
newpath = "../Images/Gallery/" + uploadedFile.FileName;
try
{
updtpanel.Visible = true;
sb.Append("<div class=" + "\"dataload\"" + ">");
sb.Append("<img class=" + "\"loadimg\"" + "src=" + "\"" + newpath.ToString() + "\"" + " />");
sb.Append("<textarea class=" + "\"txtdes\"" + "id=" + "\"" + textid + "\"" + "></textarea>");
sb.Append("</div>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
sb.Append("</div>");
d.InnerHtml = sb.ToString();
updtpanel.Controls.Add(d);
updtpanel.Controls.Add(btnsave);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);
}
}
请让我知道哪个是创建动态控件的好方法?