Add onclick event to dynamically generated link

What I'm trying to do is set up a dynamically created link using the onClick command, so clicking on it will start the method in the code. This is my code:

protected void Page_Init(object sender, EventArgs e) { LoadLeftSide(); } private void LoadLeftSide() { string filepath = Server.MapPath("DataSource.xml"); List<Post> list = PostHelper.GetAllPosts(filepath); HtmlTable table = FindControl("tbl") as HtmlTable; HtmlTableRow hearderrow = new HtmlTableRow(); HtmlTableCell heardercell = new HtmlTableCell(); heardercell.InnerText = "Posts:"; hearderrow.Cells.Add(heardercell); table.Rows.Add(hearderrow); foreach (Post p in list) { HtmlTableRow row = new HtmlTableRow(); HtmlTableCell cell1 = new HtmlTableCell(); LinkButton lnkPost = new LinkButton(); lnkPost.ID =string.Format("{0}" ,Guid.NewGuid()); lnkPost.Attributes.Add("runat", "server"); lnkPost.Text = p.Title; // lnkPost.CommandName = p.Id.ToString(); // lnkPost.CommandArgument = p.Id.ToString(); //lnkPost.Command += new CommandEventHandler(this.onLinkClick); lnkPost.Click += new EventHandler(this.onLinkClick); cell1.Controls.Add(lnkPost); row.Cells.Add(cell1); table.Rows.Add(row); } table.DataBind(); } protected void onLinkClick(object sender, EventArgs e) { string filepath = Server.MapPath("DataSource.xml"); int id = 1; Post post=PostHelper.GetPostById(id, filepath); lblDescription.Text = post.Description; } 
+4
source share
2 answers

Create all the dynamic links in the Page_PreInit handler and recreate the same hierarchy on each page. Then ASP.NET will be able to handle the OnClick event for the dynamic link.
And you do not need it

 lnkPost.Attributes.Add("runat", "server"); 

Perhaps managing the ASP.NET Menu would be more appropriate? It supports XML binding to XPath

+1
source

In this example, a button is added and the click function "delete" is set, which deletes the new button when pressed ...

see: Bind dynamic button using jQuery?

 function addNewButton() { $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />"); $("#sweetness").click(function() { $(this).remove(); }); } 
-1
source

Source: https://habr.com/ru/post/1337999/


All Articles