Chris’s ASP.Net Blog

April 29, 2008

Dynamic Javascript Dropdowns

Filed under: Uncategorized — Tags: , , , , — snakeman65 @ 2:39 pm

So I was recently creating a form with dynamic dropdown lists (populated clientside by javascript). Unfortunately, because the options in this box don’t match what the server thinks are the options the first error you get is along the lines of:

‘dropReasonCode’ has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

The way to get around this is to register all of the possible options in the render event of the page like so:

protected override void Render(HtmlTextWriter writer)
        {
base.Render(writer);
Page.ClientScript.RegisterForEventValidation(yourdropdownboxname.UniqueID, "0001");
Page.ClientScript.RegisterForEventValidation(yourdropdownboxname.UniqueID, "0002");
etc....
        }

This allows the page to post back, unfortunately, when you look at the selectedindex/selectedvalue of the dropdown you’ll find that it has ignored any selection that wasn’t in the box when the server created it! Now there are lots of ways around this, I know of two which I will detail:

  • Use javascript attached to the onchange of the dropdown to copy the value to a hidden field then read from that on the server.

I used to use this but I now feel that this is too clunky but if its what you want here’s the code I used:

In the codebehind:

if (txtDate.Attributes["onchange"] == null)
            {
                dropdownname.Attributes.Add("onchange", "javascript:copyvalue(this.options[this.selectedIndex].value);");
            }

and in the front:

function copydate(selected)
{
document.getElementById("<%=hiddenfield.ClientID %>").value = selected;
}
  • Use the Request.Form collection to read the values

This solution is much more elegant (though i’m sure there is something better still). However, there is a gotcha, in asp.net you can’t just use the id of the object, you have to use its client id, further to this, the client id will have underscores in it while the request.form collection uses $ symbols so this has to be dealt with, leaving the final code to retrieve a value:

Update: The reason I was having to use the Replace function (which subsequently broke when I moved server!) was because the request.form collection doesn’t use clientid it uses uniqueid!

Blog at WordPress.com.