Search code examples
c#asp.netbuttoncommandargument

ASP.NET button CommandArgument using <% %>


I have the following snippet of code in my .aspx file, I want the button to send the ID to the code behind.

<%List<Notes> CommentsList = FindNotes(ParentNote.ID); %>
        <%foreach (var comment in CommentsList) { %>
            <div id="note" class="tierTwo"><p><%: comment.Content %></p><ul><li><%: comment.AddedDate %></li><li>20:29</li><li><%: comment.AddedByName %></li><li><a href="#" onclick="showAddComment(addComment<%:comment.NoteID%>)" class="but">Add comment</a></li></ul> >
                <div id="addComment<%:comment.NoteID%>" class="tierOne" style="display:none">
                    <asp:TextBox ID="commentreplytext" runat="server" rows="4"> </asp:TextBox>
                    <asp:HiddenField id="ParentIdReply" value='<%=comment.NoteID%>' runat="server" />
                    <asp:Button ID="Button2" runat="server" Text="Add" CommandArgument="<%: comment.NoteID%>" OnCommand="Add_Comment" /> 
                </div>
            </div>

The code behind currently looks like this

 protected void Add_Comment(object sender, CommandEventArgs e)
 {
    string uniqueNoteID = e.CommandArgument.ToString(); 
 }

The command argument is getting sent to the Add_Comment method but it returns "<%: comment.NoteID%>" rather than the value it represents. This way of retrieving the NoteID value works fine when setting the div id so I don't know why it is causing an issue in the commandArgument.


Solution

  • <asp:Repeater runat="server" id="repeater1">
    
    <ItemTemplate>
    <div id="note" class="tierTwo"><p><%# Eval("Content") %></p><ul>
    <li><%# Eval("AddedDate") %></li><li>20:29</li>
    <li><%# Eval(AddedByName") %></li><li>
    <a href="#" onclick='showAddComment(addComment<%#Eval("NoteID")%>)' class="but">Add comment</a></li></ul> 
                    <div id='addComment<%# Eval("NoteID") %>' class="tierOne" style="display:none">
                        <asp:TextBox ID="commentreplytext" runat="server" rows="4"> </asp:TextBox>
                        <asp:HiddenField id="ParentIdReply" value='<%#Eval("NoteID")%>' runat="server" />
                        <asp:Button ID="Button2" runat="server" Text="Add" CommandArgument='<%#Eval("NoteID")%>' OnCommand="Add_Comment" /> 
                    </div>
                </div>
    </ItemTemplate>
    </asp:Repeater>
    

    .cs page:

    repeater1.DataSource = FindNotes(ParentNote.ID);
    repeater1.DataBind();