Get value of Id not displayed in the Repeater from

2019-07-29 06:51发布

问题:

I'm having a problem trying to get the value of the ID item that has been clicked in an asp.net Repeater. My Repeater has an image that opens a dialog, and from that dialog opened, when I click Approve, I would like to get this value in the .cs file when I'm redirected because the ApproveChange_Click event. I'm not doing any DataBinder.Eval to the Id I want to retrieve in the Repeater. How can I accomplish that? If I use session variables, where I can set up the value in the .aspx page and how. Thanks in advance!

This is the Repeater:

<tr class="<%# Container.ItemIndex % 2 != 0 ? "" : "odd" %>">
     <td class ="approval-img"><a class ="approvalDialog" href='#'><img src="/Images/Approve.png" alt ="Approve"/></td></a>
     <td class ="approval-img"><a class ="declineDialog" href='#'><img src="/Images/Decline.png" alt ="Decline"/></td></a>
     ...
</tr>

And this the dialog:

<div id="approval-form" style="display: none; cursor: default">
    <div class="approve-change">
        <ul>
        <li>
            <p><label>Reason</label></p>
            <textarea id="txtReason" runat="server" cols="1" rows="1" class="required"></textarea><br />
        </li>
        <li>
            <span>
            <asp:Button ID="btnApprove" runat="server" CssClass="blue" Text="Approve" ToolTip = "Approve" OnClick="ApproveChange_Click" />
            <button id="btnCancelApprove" class="blue">Cancel</button>
            </span>
        </li>
        </ul>
    </div>
</div>

回答1:

You can use the button's NamingContainer property to get the RepeaterItem. But it's not clear where you have stored the ID if you are "not doing any DataBinder.Eval to the Id".

So i would recommend to use for example a HiddenField for this, use Eval to apply the ID to it's Value property.

Somewhere in the repeater:

<asp:HiddenField ID="HiddenID" runat="server" Value='<%# Eval("ID") %>' />

Now you can get it in following way:

protected void ApproveChange_Click(Object sender, EventArgs e)
{
    Button btn = (Button) sender;
    RepeaterItem item = (RepeaterItem)  btn.NamingContainer;
    HiddenField idField = (HiddenField) item.FindControl("HiddenID");
    int ID = int.Parse(idField.Value);
}


回答2:

Here is the solution that I have found: First: change the tag in the repeater for ImageButton, for have the chance to send a command argument to the event

<td class ="approval-img"><asp:ImageButton runat="server" CommandArgument = '<%# Eval("aux_approvalId")%>'  OnClick="getApprovalID_approve" ToolTip="Approve" ImageUrl="/Images/Approve.png" /></td>

So, when I'm redirected to OnClick event, with this, I get the ID and after the dialog is opened.

ImageButton btn = (ImageButton)(sender);
Session["ApprovalID"] = btn.CommandArgument;
string script = "OpenApprovalDialog();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "", script, true);