How to get control value after Javascript refresh

2019-09-02 03:36发布

问题:

I have a page that has a popup modal window and the modal returns a value to the page and then refreshes it. I need to be able to get the value in the code-behind of the page when it is refreshed but the value of the text-box control that it is returned to is always "" after refresh.

How can I get the value of the one I returned using JS?

The code is added at a test at the moment as I try to get the value of the textbox which has contents before it is refreshed.

protected void Page_Load(object sender, EventArgs e) {
    TranslatePage.ObjectsSetup(Page.Controls, 3);
    GetUserInfo();
    if (txtCustomerType.Text != "" && txtCustomerType.Text != lblTempCustType.Text) {
        SearchCustType(txtCustomerType.Text);
    }
    SetupControls();
    string test;
    test = txtCustomerType.Text;
}

回答1:

I had similar situation but in my case i had DropDown list box which is getting filled with javascript. So to get the selected value after the javascript has been fired to fill the dropdown list, i have used one additional method the get value which is

public static string GetValueOfControl(WebControl ServerControl)
    {
        string IdOfControl = ServerControl.UniqueID;
        NameValueCollection PostBackFormControls = HttpContext.Current.Request.Form;
        if (PostBackFormControls.AllKeys.Length == 0)
            return null;
        string value = PostBackFormControls[IdOfControl];
        if (value == null)
        {
            int index = 0;
            for (; index < PostBackFormControls.AllKeys.Length; index++)
                if (PostBackFormControls.AllKeys[index].EndsWith(IdOfControl))
                    break;
            if (index < PostBackFormControls.AllKeys.Length)
                return PostBackFormControls[index];
            else
                return null;
        }
        else
        {
            return value;
        }
    }

and to get the value I used

string District = Convert.ToString(GetValueOfControl(dropDownListBoxDistrict));

So, all u need to do is to add the method and pass your text box to get its value as,

string test = Convert.ToString(GetValueOfControl(txtCustomerType));

I am sure, it will work for u