2017-12-26 3 views
-1

「カートに入れる」ボタンをクリックしたときに商品を追加したいのですが、リピーターでどうすればいいですか? onclickイベントの生成方法は?c# - リピーターでクリックイベントを生成する方法

<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> 

答えて

1

Webフォーム

これは、項目ごとに一つのボタンを生成します。リピーターが最後に索引を連結しているため、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がクリックされた項目を示します。別のオプションは、属性として設定する代わりに、インデックスをハンドラに渡すことです。

関連する問題