如何从代码后面添加服务器端锚到div?

时间:2011-10-25 18:55:31

标签: c# asp.net anchor server-side code-behind

请先看下面的aspx:

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

MyAnchor1 Serverside点击事件完美无缺! 我想从代码背后做出类似的东西:

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评论后(An Anchor With ID) - &gt;仍然无法正常工作

输出html是这样的:

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

提前致谢

1 个答案:

答案 0 :(得分:2)

这不是在ASP.NET中创建动态控件的正确方法。您可以使用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
}