更改标签的值并隐藏asp转发器中的图像按钮

时间:2012-04-16 23:32:44

标签: c# asp.net .net linq repeater

我有一个asp转发器,它在ItemTemplate中有一些字段。转发器中的每个项目都有一个“添加到购物车”的asp:ImageButton和一个不可见的asp:Label。代码如下所示:

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="addToCart">
        <HeaderTemplate>
            <table id="displayTable"> 
        </HeaderTemplate>
        <ItemTemplate>
           <td>
                <!-- fields like name, description etc in the repeater are present; i've omitted to show them here-->
                <asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>       
                <asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />
           </td>
        </ItemTemplate>
        <FooterTemplate>
           </table>
        </FooterTemplate>
</asp:Repeater>

当点击转发器中的特定ImageButton时,我试图将“添加到购物车”显示为其相应Label的文本,并使点击的ImageButton Visible = false。我已经尝试使用OnItemCommand函数用于ASP:Repeater。方法是“addToCart”: &LT;&GT;

void addToCart(Object Sender, RepeaterCommandEventArgs e)
{
    Cart cart = new Cart();
    cart.instrument_id = //id of product from repeater based on user click
    String userName = Membership.GetUser().ToString();
    cart.user_name = userName;
    cart.quantity = 1;
    var thisLbl = (Label)e.Item.FindControl("addedToCartLabel");
    var thisImg = (ImageButton)e.Item.FindControl("addToCartImg");
    try
    {
        database.Carts.InsertOnSubmit(cart);
        database.SubmitChanges();

        thisImg.Visible = false;
        thisLbl.Text = "Added to Cart!";
        thisLbl.Visible = true;

    }
    catch (Exception ex)
    {
        thisImg.Visible = false;
        thisLbl.Text = "Processing failed;please try again later";
        thisLbl.Visible = true; ;
    }


}

正确填充aspx页面。但是,当我单击转发器中的任何ImageButton时,我收到以下错误:

  Server Error in '/mysite' Application.
    Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. 
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback
or callback data for validation.

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

我建议使用客户端javascript而不是服务器端调用吗?

<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>       
<asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />

变为

<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>       
<asp:ImageButton ID="addToCartImg" runat="server" onclick="javascript:function() { this.this.style.display='none'; document.getElementById(this.parentNode.firstChild.id).style.display='block'; }"  ImageUrl="hi.jpg" Width="75px" Height="50px" />