Question

I have an asp.net site (C# backend) that loads information from a database. It allows users to save information by clicking an add/delete button. This button dynamically changes based on whether or not the user has saved it or not. I am using commandnames and arguments to pass the data. When the button is pressed, it stays on the same page and just updates the look (does a postback). This is working well under normal circumstances. However, if the user navigates away from the page, and then back to the page, it re-executes the OnClick method for the button that was pressed.

I know that it is doing a postback when using the back button, but why does it fire the last onclick? Is this normal behavior? I have tried disabling caching, and trying to make the page expire and everything but nothing works. The data is shown in a repeater, and ViewState is enabled...from what I've read I'm wondering if that is the cause. However, If ViewState is disabled, then no results show up on postback. If it is the problem, is there some other way to get the data to dynamically update in the Repeater without using Viewstate? Not sure if it will be of any help, but the button markup that shows the commandname and argument is below.

<asp:Repeater ID="ItemRepeater" runat="server" EnableViewState="true">
    <!--Lots of other code before pressed button-->
    <asp:Button ID="additembutton" runat="server" OnClick="AddDelOnClick" Text='<%# textToDisplay((int)Eval("isSaved")) %>'
     CommandName='<%# DataBinder.Eval(Container.DataItem, "isSaved").ToString().Trim() %>' 
     CommandArgument='<%# DataBinder.Eval(Container.DataItem, "itemnumber").ToString().Trim() + "~" +
       DataBinder.Eval(Container.DataItem, "department").ToString().Trim() + "~" +
       DataBinder.Eval(Container.DataItem, "itemdescription").ToString().Trim() + "~" +
       DataBinder.Eval(Container.DataItem, "isSaved").ToString().Trim()%>'
     CssClass='<%# cssClassToDisplay((int)Eval("isSaved")) %>' /></td></tr>
Was it helpful?

Solution 2

Got this one quickly...should have held out just a little longer before asking. Changed:

CommandName='<%# DataBinder.Eval(Container.DataItem, "isSaved").ToString().Trim() %>'

to

CommandName='AddorDelete'

and changed the backend code to only change the commandargument.

OTHER TIPS

I will go with "normal behavior". This has always been a thorn for me, and my super elegant solution is to wrap the postbacks in an UpdatePanel...which leads to other issues and needs, but at least the back button doesn't trigger anything, and I can never seem to control my end users.

    <asp:ScriptManager id="smPage" runat="server"/>

    <asp:UpdatePanel id="upPnlRepeater" runat="server">
        <ContentTemplate>
            <asp:Repeater id="YourRepeater">
            </asp:Repeater>
        </ContentTemplate>
    </asp:UpdatePanel>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top