Invalid postback

Hello, I have a gridview control with a button in a template column. When the button is clicked an update statement is executed. This used to work fine, but for some reason it is now throwing this error:

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.

Any help would be great!
gogetsomeAsked:
Who is Participating?
 
DBAduck - Ben MillerConnect With a Mentor Principal ConsultantCommented:
Don't you have to add OnSelectedIndexChanged to the gridview definition?

<asp:GridView ID="CartGrid" runat="server" AutoGenerateColumns="False" BackColor="White"
                    BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataKeyNames="id"
                    DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" Width="700px" Font-Names="Verdana" Font-Size="Small"
     OnSelectedIndexChanged="CartGrid_SelectedIndexChanged">

Ben.
0
 
TornadoVCommented:
Try to put the following line in <system.web> section of your web.config:
<pages enableEventValidation="false" />
0
 
DBAduck - Ben MillerPrincipal ConsultantCommented:
Well, this will get rid of the error but will not protect against callback events being cross scripted.

So you may want to use the ClientScriptManager.RegisterForEventValidation with the script that calls back so that your script is not getting hijacked and causing other issues.  Don't just turn it off to get rid of it, unless that is the last alternative.  And if you do that, then you should employ some checks to make sure that it is your code that called the postback.

Ben.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
gogetsomeAuthor Commented:
Thank you TornadoV for your help. I added the enableEventValidation="False" to the web.config. The error does not occur, but the button does not fire the SelectedIndexChanged:

This is just weird. It used to work fine.

Some code:

<%@ Page Language="VB" MasterPageFile="~/clients/clientsMasterPage.master" AutoEventWireup="false" CodeFile="myCart.aspx.vb" Inherits="clients_myCart" title="Clients - My Cart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  <table style="width: 100%">
 

 <ItemTemplate>
                               <asp:ImageButton ID="ImageButton1" runat="server" CommandName="select" ImageUrl="~/clients/graphics/btnDelete.jpg" />
 </ItemTemplate>

Code behind which never fires:
    Protected Sub CartGrid_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CartGrid.SelectedIndexChanged
        Dim row As GridViewRow = CartGrid.SelectedRow
        CartGrid.SelectedRowStyle.Reset()
        lblId.Text = (CType(row.Cells(4).FindControl("label4"), Label)).Text
        lblQuantity.Text = (CType(row.Cells(3).FindControl("label3"), Label)).Text
        lblIdNum.Text = (CType(row.Cells(6).FindControl("label6"), Label)).Text
        updateDataBase()
    End Sub
    Sub updateDataBase()
        lblId.Text = ID

        Dim cn As SqlConnection = New SqlConnection("user id=DB_210580_qualweb_user;data source=test;persist security info=True;initial catalog=test;password=test")

        Dim row As GridViewRow = CartGrid.SelectedRow
        lblId.Text = (CType(row.Cells(4).FindControl("label4"), Label)).Text
        lblQuantity.Text = (CType(row.Cells(3).FindControl("label3"), Label)).Text
        lblIdNum.Text = (CType(row.Cells(6).FindControl("label6"), Label)).Text


        Try
            Dim cmd As SqlCommand = cn.CreateCommand

            cmd = New SqlCommand("cssp_addItem", cn)
            cmd.CommandType = CommandType.StoredProcedure

            With cmd
                cmd.Parameters.Add("@lblId", SqlDbType.Int).Value = Convert.ToInt32(lblId.Text)
                cmd.Parameters.Add("@lblQuantity", SqlDbType.Int).Value = Convert.ToInt32(lblQuantity.Text)
                cmd.Parameters.Add("@lblIdNum", SqlDbType.Int).Value = Convert.ToInt32(lblIdNum.Text)
            End With
            If Not cn.State = ConnectionState.Open Then

                cn.Open()

            End If
            cmd.ExecuteNonQuery()

        Catch ex As Exception
            Response.Write(ex.ToString)

        Finally

            If Not cn.State = ConnectionState.Closed Then

                cn.Close()
                cn = Nothing

            End If
            CartGrid.DataBind()

        End Try
    End Sub


0
 
gogetsomeAuthor Commented:
dbaduck, I'm not sure how to do that. Can you provide more information on how to do that?
0
 
TornadoVCommented:
I don't see CommandArgument='<%# Eval("ITEM_ID") %>' in your ItemTemplate block:

<ItemTemplate>
                               <asp:ImageButton ID="ImageButton1" runat="server" CommandName="select" ImageUrl="~/clients/graphics/btnDelete.jpg" />
 </ItemTemplate>

What is the ID field in your gridview?
0
 
gogetsomeAuthor Commented:
Sorry, I should have added more code. Here is all of the page code:

<%@ Page Language="VB" MasterPageFile="~/clients/clientsMasterPage.master" AutoEventWireup="false" CodeFile="myCart.aspx.vb" Inherits="clients_myCart" title="Clients - My Cart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  <table style="width: 100%">
  <tr>
  <td>
      <asp:ImageButton ID="btnOrderParts" runat="server" ImageUrl="~/clients/graphics/btnOrderParts.jpg"
          PostBackUrl="~/clients/orderParts.aspx" />
      <asp:ImageButton ID="btnCheckOut" runat="server" ImageUrl="~/clients/graphics/btnCheckout.jpg"
          PostBackUrl="~/clients/checkOut.aspx" />
      <asp:Label ID="lblMessage2" runat="server" ForeColor="Red"></asp:Label></td>
  </tr>
        <tr>
            <td style="width: 600px;" valign="top">
                    <asp:GridView ID="CartGrid" runat="server" AutoGenerateColumns="False" BackColor="White"
                    BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataKeyNames="id"
                    DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" Width="700px" Font-Names="Verdana" Font-Size="Small">
                    <FooterStyle BackColor="#CCCCCC" />
                    <Columns>
                        <asp:BoundField DataField="invtId" HeaderText="Part Number" ReadOnly="True" SortExpression="invtId" />
                        <asp:BoundField DataField="descr" HeaderText="Description" ReadOnly="True" SortExpression="descr" />
                        <asp:BoundField DataField="location" HeaderText="Location" ReadOnly="True" SortExpression="location" />
                        <asp:TemplateField HeaderText="Quantity">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
                            <EditItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label4" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ShowHeader="False">
                            <ItemTemplate>
                               <asp:ImageButton ID="ImageButton1" runat="server" CommandName="select" ImageUrl="~/clients/graphics/btnDelete.jpg" />
                            </ItemTemplate>
                            <ItemStyle HorizontalAlign="Center" Width="56px" Wrap="False" />
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="idNum" InsertVisible="False" SortExpression="idNum" Visible="False">
                            <EditItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Eval("idNum") %>'></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label6" runat="server" Text='<%# Bind("idNum") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="#CCCCCC" />
                        <EmptyDataTemplate>
                            There are no parts in your cart.
                            <asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="~/clients/orderParts.aspx">Add Parts to Cart</asp:LinkButton>
                        </EmptyDataTemplate>
                </asp:GridView>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:test%>"
                    DeleteCommand="DELETE FROM [tempCart] WHERE [id] = @id" InsertCommand="INSERT INTO [tempCart] ([invtId], [descr], [location], [quantity], [username]) VALUES (@invtId, @descr, @location, @quantity, @username)"
                    SelectCommand="SELECT [idNum], [invtId], [descr], [location], [quantity], [username], [id] FROM [tempCart] WHERE ([username] = @username) ORDER BY [invtId]"
                    UpdateCommand="UPDATE [tempCart] SET [quantity] = @quantity WHERE [id] = @id">
                    <DeleteParameters>
                        <asp:Parameter Name="id" Type="Int32" />
                    </DeleteParameters>
                    <UpdateParameters>
                     
                        <asp:Parameter Name="quantity" Type="String" />
                       <asp:Parameter Name="id" Type="Int32" />
                    </UpdateParameters>
                    <SelectParameters>
                        <asp:ControlParameter ControlID="lblUsername" Name="username" PropertyName="Text"
                            Type="String" />
                    </SelectParameters>
                    <InsertParameters>
                        <asp:Parameter Name="invtId" Type="String" />
                        <asp:Parameter Name="descr" Type="String" />
                        <asp:Parameter Name="location" Type="String" />
                        <asp:Parameter Name="quantity" Type="String" />
                        <asp:Parameter Name="username" Type="String" />
                    </InsertParameters>
                </asp:SqlDataSource>
            </td>
        </tr>
        <tr>
            <td style="width: 600px; height: 5px;" valign="top">
                <asp:Label ID="lblUsername" runat="server" Visible="False"></asp:Label><asp:Label ID="lblId" runat="server" Visible="False"></asp:Label><asp:Label ID="lblQuantity" runat="server" Visible="False"></asp:Label><asp:Label ID="lblMessage" runat="server" Visible="False"></asp:Label><asp:Label
                        ID="lblIdNum" runat="server" Visible="False"></asp:Label></td>
        </tr>
        <tr>
            <td style="width: 600px">
                </td>
        </tr>
    </table>
</asp:Content>
0
 
TornadoVCommented:
I think the problem here is that you have your ViewState set to 'true' and the CartGrid.DataBind() is being called on every PostBack.   I'm assuming that this causes the internal identitiy of the image button to change (as seen by ASP 2.0) compared to the original page and causes the security exception.

In my opinion you have two options:
1. Set EnableViewState = 'false'

2. If you don't want to disable viestate, then re-set databinding:
CartGrid.DataSourceID = ""  -- Remove the old binding
CartGrid.DataSourceID = "SqlDataSource1"
CartGrid.DataBind()

Hope this helps.
0
 
gogetsomeAuthor Commented:
Thank you both for helping! Tornado I appreciate you sticking with me. It appears that the selectedindexchange was not firing. so my codebehind was never executing. I added the select command button,(got rid of the image button) changed it to my image and it works fine.

Thanks dbaduck for the slap up side the back of the head.

The image button should have fired the event.... it was given the command name of select. Correct , I did not have the
OnSelectedIndexChanged="CartGrid_SelectedIndexChanged">

Thanks again to you both.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.