简体   繁体   English

Ajax调用C#代码后失去隐藏字段的值

[英]loosing hidden field value after ajax call to c# code

Using jquery 1.7.2 and .net 4.0 使用jQuery 1.7.2和.net 4.0

I have a json ajax call that sets the value of a asp hidden field on my form. 我有一个json ajax调用,它设置表单上的asp隐藏字段的值。 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代码时,该值为空。 ASPX code: ASPX代码:

    <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: 后面的C#代码:

#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. 由于ajax调用,隐藏字段将不会更新。 You must use the data which is returned by the ajax call. 您必须使用ajax调用返回的数据。

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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