简体   繁体   English

ASP.NET动态按钮?

[英]ASP.NET Dynamic Button?

I can't find solution for my problem. 我找不到解决我问题的方法。 I'm making web shop. 我正在网上商店。 I have list of products which i'm taking from database. 我有从数据库中提取的产品列表。 I'm sending all of them to html with foreach 我用foreach将它们全部发送到html

<% foreach (var product in productList) { %>
            <h1><%= product.Name  %>  &nbsp;

I want to have button "Buy Now" for each of products and after clicking want to have id product property in sender. 我要为每个产品设置按钮“立即购买”,然后单击要在发件人中拥有id产品属性。 What would be best way to do that ? 最好的方法是什么?

Generate buttons with different IDs & properties that result in the same OnClick method in the code behind. 生成具有不同ID和属性的按钮,从而在后面的代码中产生相同的OnClick方法。

In the code behind: 在后面的代码中:

// Generate elements for each product  
foreach (var product in productList)  
{  
   Button btn = new Button();  
   btn.CommandArgument = product.ID; // This would be your product ID  
   btn.Text = "Buy Now";  
   btn.Click += Btn_Click;  

   this.Products.Controls.Add(btn);  
}

In the markup: 在标记中:

<div id="Products" runat="server">
</div>

Or either use a WebHandler (.ashx) which acts as an endpoint to retrieve a request and process to return data. 或者使用WebHandler(.ashx)作为端点来检索请求并处理返回数据。 Helpful for async as well. 有助于异步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM