views:

215

answers:

1

I have the following JavaScript to toggle a dropdownlists in a ASP.NET page , which gets called when I click a button. I have like 4-5 dropdownlist/Toggle button pair. Each toggle button toggles the enable/disable property on the associated dropdownlist.

function toggleDisableDropDown(dropDownID) {
  var element = document.getElementById(dropDownID); // get the DOM element

  if (element) { // element found
    element.disabled = !element.disabled; // invert the boolean attribute
  }

  return false; // prevent default action
}

But one of my dropdownlist needs to do a postback everytime, I pick an item to populate another dropdownlist, What I noticed is that on this postback all of my other dropdownlist which were disabled by javascript(user clicks on the toggle button for these dropdownlist) gets enabled.

What is happening here? and how can I fix it?

+1  A: 

Javascript DOM manipulation has no relevance to the control's saved state on the server. Changing the enabled property on the dropdownlists on the client side will not be known to the control state on the server.

Posting back re-creates the dropdownlist's using the last known state of the control. If you want to have them re-rendered using the last state on the client, you'll need to post some client tracking information as well. You could track each dropdownlist's client state in a hidden field, and use the posted value from those hidden fields to update the Enabled property of the dropdownlist on the server.

//Html
<input type="hidden" name="_trackingDropdown1" value="true" />

//Client Javascript
function toggleDisableDropDown(dropDownID) {
  var element = document.getElementById(dropDownID); // get the DOM element
  var trackingField = document.getElementById("_tracking" + dropDownID);

  if (element) { // element found
    element.disabled = !element.disabled; // invert the boolean attribute
    trackingField.value = element.disabled;
  }

  return false; // prevent default action
}

//On Server during postback handling
if (Request.Params["_trackingDropDown1"] != null)
{
    bool.TryParse(Request.Params["_trackingDropDown1"], out DropDownList1.Enabled);
}
womp
I get the following error onbool.TryParse(Request.Params["_trackingDropDown1"], out DropDownList1.Enabled)A property or indexer may not be passed as an out or ref parameter
Nevin Mathai
Oh, just use a temporary variable then. bool result; bool.TryParse(Request.Params["_trackingDropDown1"], out result); DropDownList1.Enabled = result;
womp