我想在我点击“添加到购物车”按钮时添加产品但在转发器中我该怎么办?如何生成onclick事件?
<div class="product">
<div class="text">
<h3><%#Eval("Name")%></h3>
<p style="text-align:center;"><b> <%#Eval("qty") %></b></p>
<p class="price">Rs.<%#Eval("Price") %></p>
<p class="buttons">
<button runat="server" id="b1" onclick="b1_cl" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</button>
</p>
</div>
</div>
网络表单
这将为每个项目生成一个按钮。在Html级别,id仍然是唯一的,因为转发器在末尾连接索引。
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="Repeater1_ItemCreated" >
<ItemTemplate>
<button type="submit" runat="server" id="myButton" class="btn btn-primary">
<i class="fa fa-shopping-cart"></i>Add to cart
</button>
</ItemTemplate>
</asp:Repeater>
代码背后
添加处理程序和项索引,因为我稍后将需要它。
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var button = (HtmlButton)e.Item.FindControl("myButton");
if (button != null)
{
button.Attributes["index"] = e.Item.ItemIndex.ToString();
button.ServerClick += new EventHandler(MyButton_Click);
}
}
最后点击处理程序:
protected void MyButton_Click(object sender, EventArgs e)
{
string index = ((HtmlButton)sender).Attributes["index"];
}
变量index
告诉您单击了哪个项目。另一个选项是将索引传递给处理程序,而不是将其设置为属性。