[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Invalid postback

Posted on 2006-05-05
9
Medium Priority
?
761 Views
Last Modified: 2007-10-18
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!
0
Comment
Question by:gogetsome
  • 4
  • 3
  • 2
9 Comments
 
LVL 11

Expert Comment

by:TornadoV
ID: 16615970
Try to put the following line in <system.web> section of your web.config:
<pages enableEventValidation="false" />
0
 
LVL 25

Expert Comment

by:DBAduck - Ben Miller
ID: 16616631
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
 

Author Comment

by:gogetsome
ID: 16616660
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:gogetsome
ID: 16616682
dbaduck, I'm not sure how to do that. Can you provide more information on how to do that?
0
 
LVL 11

Expert Comment

by:TornadoV
ID: 16616791
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
 

Author Comment

by:gogetsome
ID: 16616857
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
 
LVL 11

Expert Comment

by:TornadoV
ID: 16616960
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
 
LVL 25

Accepted Solution

by:
DBAduck - Ben Miller earned 2000 total points
ID: 16616987
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
 

Author Comment

by:gogetsome
ID: 16617259
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

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month18 days, 18 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question