Tom smith
Tom smith

Reputation: 680

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.

Upvotes: 0

Views: 4175

Answers (2)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

<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();

Upvotes: 0

user489998
user489998

Reputation: 4521

Unfortunately you can't use <%%> code blocks in .NET controls. It's to do with the order things get rendered in. You'll have to set the CommandArgument in the code behind when you build the page. You could do that if you built the page using a repeater rather than a for each in the page.

Upvotes: 1

Related Questions