2011-10-25 67 views
0

PLZ看到下面的aspx第一:如何將服務器端錨添加到div代碼後面?

<div id="divFilesBody"> 
       <div class="divFilesBody_Row"> 
       <%= Files %> 
       <a id="MyAnchor1" runat="server" OnServerClick="AnchorForDwonload_Click">Server Side Anchor 1</a> 
      </div> 

MyAnchor1 Serverside集團click事件的作品完美!
我要讓類似的東西從後面的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Collections; 
using System.IO; 
using FileExplorer.Classes; 

namespace FileExplorer.en 
{ 
    public partial class Download : System.Web.UI.Page 
    { 
     public string Files = ""; 
     protected void Page_Load(object sender, EventArgs e) 
     { 
... 
      foreach (FileInfo f in dir.GetFiles("*.*")) 
      { 
       Files += "<a class='MyAnchor2' runat='server' OnServerClick='AnchorForDwonload_Click'>"; 
       Files += "Server Side Anchor 2"; 
       Files += "</a>"; 
      } 
     Files += "<a id='MyAnchor3' runat='server' OnServerClick='AnchorForDwonload_Click'>"; 
     Files += "Server Side Anchor 3"; 
     Files += "</a>"; 
     } 

     protected void AnchorForDwonload_Click(object sender, EventArgs e) 
     { 
      Response.Write("Server Side Anchor Works"); 
     } 

    } 
} 

但MyAnchor2不燒頁面加載後工作...
我怎樣才能解決這個問題呢?

編輯
我加入MyAnchor3評論後(錨帶ID) - >仍不工作

輸出HTML是這樣的:在

 <a id='MyAnchor3' runat='server' OnServerClick='AnchorForDwonload_Click'> 
     Server Side Anchor 3 
     </a> 

感謝advance

+0

哪裏'ID '爲myanchor2? – JonH

+0

@JonH感謝commnet /你是對的/我應該添加他們中的很多/所以我刪除了ID! – MoonLight

+0

試試這個應該可以幫到你。 http://stackoverflow.com/questions/2351225/how-to-dynamically-render-asp-net-controls-from-string – 2011-10-25 19:29:21

回答

2

這不是在ASP中創建動態控件的正確方法。淨。您可以使用LinkBut​​ton控件來實現這一目標:

你應該做這樣的,而不是什麼:

標記:

<asp:Panel ID="pnlFilesBody" runat="server"> 
    <!-- resolves to a DIV --> 
</asp:Panel> 

代碼隱藏:

protected override void OnInit(EventArgs e) 
{ 
    //create controls at every page load and assign the same ids to the controls 
    //to preserve click events 

    foreach (FileInfo f in dir.GetFiles("*.*")) 
    { 
     //create a new linkbutton 
     LinkButton btn = new LinkButton(); 
     btn .ID = String.Format("lnk_{0}", pnlFilesBody.Controls.Count); 
     btn.Click += new EventHandler(btn_Click); 
     btn.Text = String.Format("Server Side Anchor {0}", pnlFilesBody.Controls.Count); 

     //add the linkbutton to the files body panel 
     pnlFilesBody.Controls.Add(btn); 
    } 
} 

protected void btn_Click(object sender, EventArgs e) 
{ 
    //put your click event logic here 
} 
相關問題