I have an ASP.Net dropdown list that is populated using javascript like this:
Dropdown list:
<asp:DropDownList ID="Ddl" runat="server" AutoPostBack="true"
EnableViewState="true"></asp:DropDownList>
The javascript code that populates the dropdown list with “text” is:
var select = document.getElementById('<%= Ddl.ClientID %>');
var option = document.createElement("option");
option.value = '1';
option.innerHTML = "Text";
select.appendChild(option);
It gets filled just fine in client side. I added a button that is supposed to run on server side. On the server side when I try to retrieve the ddl selected value; it gives an exception (Object reference not set to an instance of an object.)
I understand that the ASP.Net ddl control loses the content once form is sent to server?
How would I tackle this issue? I tried putting the value in hidden field and try using Request.Form["HiddenField"].toString(); but it gives the same error. Any help?
As you state, you can’t populate a dropdown on the client side and have the server side know the
ListItemobjects are there. That’s because they don’t get posted back to the server: only the selected value does.You might have better luck not even using a
DropDownList. Create the dropdown as an HTMLselecttag. Be sure to set thenameattribute (or it won’t get picked up on postback). Then use theRequest.Formcollection to access the selected value for the HTMLselect.The only reason to use a
DropDownListthat I can think of, given what you’ve told us, would be if at some point you intend to bind it on the server side, from server-side data, or if you want to change its appearance based on a server-side calculation, but don’t want to set up an Ajax call. If you don’t want to do either of these things, aselectmight serve you better.