Search code examples
javascriptc#jquerypostbackviewstate

Hot to update Postback data directly using ViewState or some other method to clear hidden field?


I have a hidden field that stores some Ids of items to be updated when a button is clicked on the page. This is working fine. However, if the user clicks the Update button, then waits for page to reload, and then refreshes the page manually (using browser Refresh button), the data is resubmitted and creates duplicate data in the database.

Is there a way to clear the hidden field in the Postback data so that if the user does refresh the page manually, the hidden field will be empty and no updates to the database will be made?

So far, I have tried to manually update the ViewState using the code below after the database is updated.

ViewState["hdnBulkIds"] = "";

I have also tried to exclude the hidden field from the ViewState and manually clear it using jQuery on page load.

$( document ).ready(function() {
    $('#<%= hdnBulkIds.ClientID %>').val("");
});

In both cases, I cannot seem to update the data "instance" that is sent to server on manual page refresh so the hidden field retains its original values from original button click.

I guess the question can be simplified to this: Is there a way to update the Postback data directly using ViewState or some other method to clear the hidden field?


Solution

  • This is a big issue with webforms in general and a big reason you should consider jumping ship to MVC. There may be an elegant way to handle this through webforms, but I'm not aware of any.

    Once the user submits a form the browser "remembers" that submission and the refresh will re-submit it. There is nothing you can do about that, you have to detect a second submission through other means.

    Your best/most true solution is to do a redirect after you get all of your data, and use your query parameters to re-build the page in the state it needs to be in. Then when the user refreshes the screen it will resubmit the redirect instead of the form submission.

    Page.Redirect() or something along those lines is the function that lets you do a redirect. Trouble is, a page redirect will erase all state webforms was maintaining about the page, you have to rebuild all of it.

    You also might be able to implement some sort of "CSRF" token style system. Generate a random number and store it in the user session on page load. When the user posts back, invalidate that number somehow. That way, if they post-back again with the number you can cancel the request.

    That's a hackey way of going about things, doing a redirect is the "tried tested" method to my knowledge.

    Another option is if the postback edits a value, check for duplicates or if the value is edited and if there are duplicates don't let the user double-submit.