简体   繁体   中英

loosing hidden field value after ajax call to c# code

Using jquery 1.7.2 and .net 4.0

I have a json ajax call that sets the value of a asp hidden field on my form. While stepping through the code behind I can see the value the hidden field is set but when the code returns to the aspx code the value is empty. ASPX code:

    <asp:HiddenField ID="hidden1" runat="server" />
    //dropdownlist on change event calls the function below:
     function getReport() {
            var data = { MethodName: 'myMethod', value1: value1 }
            var options = {
                url: '<%=ResolveUrl("myPage.aspx") %>',
                async: false,
                data: data,
                datatype: 'text',
                type: 'POST',
                success: function () {
                    var returnedData = $("#hidden1").val();
                    alert('returned data = ' + returnedData);
                }
            }
            $.ajax(options);
//also tried alerting the returned data here.. still empty
        }

c# code behind:

#region AJAX
        if (Request.Form["MethodName"] == "myMethod")
        {

            hidden1.Value = "please just pass this value!!!";
            return;
        }
        else
        {
            //do something different.
        }
        #endregion

I've simplified my code, hopefully not too much. and I double checked my code to make sure the hidden field value is not set elsewhere in the code.

Due to the ajax call the the hidden field will not be updated. You must use the data which is returned by the ajax call.

 function getReport() {
        var data = { MethodName: 'myMethod', value1: value1 }
        var options = {
            url: '<%=ResolveUrl("myPage.aspx") %>',
            async: false,
            data: data,
            datatype: 'text',
            type: 'POST',
            success: function (returnedData) {
                alert('returned data = ' + returnedData);
            }
        }
        $.ajax(options);
    }

code behind:

#region AJAX
if (Request.Form["MethodName"] == "myMethod")
{
     return "please just pass this value!!!";
}
else
{
     //do something different.
}

#endregion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM