0

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?

2
  • Where are you trying to get the selected value? in the SelectedIndexChanged or your button click event? If you have AutoPostBack="true" you don't need a button to submit the selection. Commented Jan 16, 2013 at 13:14
  • Thank you for the respond; It is all cleared out after Ann L reply below. thnx Commented Jan 16, 2013 at 14:44

1 Answer 1

2

As you state, you can't populate a dropdown on the client side and have the server side know the ListItem objects 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 HTML select tag. Be sure to set the name attribute (or it won't get picked up on postback). Then use the Request.Form collection to access the selected value for the HTML select.

The only reason to use a DropDownList that 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, a select might serve you better.

Sign up to request clarification or add additional context in comments.

1 Comment

Thnx I was planning to go for the Cascading DDls; and what you said makes more sense to not use server side controls if i do not have any server side binding...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.