我在Repeater中有一个图像按钮,它位于用户控件中,当我点击它时,我无法触发OnItemCommand事件。它始终给出错误:“...无效的回发或回调参数。使用...”
启用事件验证当我将图像按钮更改为链接按钮时,它不会给我错误,但它仍然不会触发OnItemCommand函数。
我找到了一些其他相关的答案(例如How to process events from Buttons inside Repeaters? And what's this EnableEventValidation thing?),但他们都说,“确保你在if(!Page.IsPostBack)块内部对转发器进行数据绑定。”我已经这样做了,但没有什么区别。
这是转发器的标记:
<asp:Repeater ID="rptExpenses" OnItemDataBound="rptExpenses_ItemDataBound" OnItemCommand="Button_Command" runat="server" >
<ItemTemplate>
<asp:ImageButton ID="ibDelete" ImageUrl="~/Images/delete.png" CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
以下是代码隐藏的一些摘录
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
rptExpenses.DataSource = ExpenseIds;
rptExpenses.DataBind();
}
}
protected void rptExpenses_ItemDataBound(object sender, RepeaterItemEventArgs e) {
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) {
var ibDelete = (ImageButton)e.Item.FindControl("ibDelete");
ibDelete.CommandArgument = e.Item.DataItem.ToString();
}
}
protected void Button_Command(object sender, EventArgs e) {
var btn = (IButtonControl)sender;
switch (btn.CommandName) {
case "Delete":
//delete it
break;
}
}
答案 0 :(得分:0)
请尝试使用此代码:
<asp:Repeater ID="rptExpenses" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ibRemove" ImageUrl="~/Images/delete.png" runat="server"
CommandName="Remove"
CommandArgument='<%# Container.DataItem %>'
OnCommand="ibRemove_Click"/>
</ItemTemplate>
</asp:Repeater>
这在后面的代码中:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
rptExpenses.DataSource = ExpenseIds;
rptExpenses.DataBind();
}
}
protected void ibRemove_Click(object sender, CommandEventArgs e)
{
var btn = (IButtonControl)sender;
switch (btn.CommandName)
{
case "Remove":
//delete it, use btn.CommandArgument to find id to remove
break;
}
}
如果您仍然收到... Invalid postback or callback argument. Event validation is enabled using ...
错误,则很可能意味着您在ibRemove_Click(...)
事件被引发之前重新绑定转发器。
答案 1 :(得分:0)
我在这个问题的答案中找到了原因:Why ItemCommand doesn't fired on My Repeater
事实证明,由于某种原因,Page的DataBind功能使转发器的控件无效,而不是第二次通过转发器的OnItemDataBound功能。