Search code examples
javascriptasp.netajaxhidden-field

Hidden field updates on server side after second button click


I have a hidden field that I am updating via Javascript once I click a button, but when I try to access it on the code behind there is no value until I click the button the second time. I am able to see the hidden field value when I inspect it via the browser.

Default.aspx

<script type="text/javascript">
    function LoadHtml(inputState, inputStateAbbr, inputProgramType, inputHealthCenter, inputCity) {

        $.ajax({
            url: omitted,
            type: "POST",
            async: false,
            data: {
                state: inputState,
                stateAbbr: inputStateAbbr,
                programType: inputProgramType,
                healthCenter: inputHealthCenter,
                city: inputCity
            },

            success: function(result) {
                document.getElementById('DataHiddenField').value = result;

            },
            error: function (jqXHR, textStatus, errorThrown) {
                //omitted
            }
        });
    }
</script>

<asp:Button ID="Button1" runat="server" OnClick="Button1_OnClick" CssClass="top-buffer" Text="Compare Sites" />

<asp:HiddenField ID="DataHiddenField" runat="server" ClientIDMode="Static" />

Code Behind

protected void Button1_OnClick(object sender, EventArgs e)
{
    RetrieveHtml();
}

private string RetrieveHtml(){
    Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey1", "LoadHtml('Alabama', 'AL', 'Program Awardee Data', 'Alabama Regional Medical Services', 'Birmingham');", true);
    return DataHiddenField.Value;
}

Solution

  • You seem to have a fundamental misunderstanding on how web pages and asp.net webforms, specifically, work. Generally when a form posts a form to a server, a request for a new page is made, the server does some work with the form variables and sends a new page as a response. There is a disconect between client side and server side at this point.

    Let's dissect your code:

    <!-- Causes a postback to the server, no javascript run yet -->
    <asp:Button ID="Button1" runat="server" OnClick="Button1_OnClick" CssClass="top-buffer" Text="Compare Sites" />
    

    Code Behind

    private string RetrieveHtml(){
      /*Tells the page to run this script - WHEN IT NEXT LOADS*/
       Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey1", "LoadHtml('Alabama', 'AL', 'Program Awardee Data', 'Alabama Regional Medical Services', 'Birmingham');", true);
       /*Gets the value from the hidden field.*/
       /*On first click the above java-script HAS NOT RUN*/
       return DataHiddenField.Value;
    }
    
    /*After the server has finished work, it sends a new page response.*/
    /*THEN the javascript runs*/
    

    So what do you need to do?