tags:

views:

573

answers:

3

Hi. This my scenerio

  1. I have a listbox with runat=server
  2. Items are added to this listbox on the client side, using javascript
  3. I would want to retrieve the items on the server side on the click of a button

The problem is in the Buttons's server side click handler, I cannot see the new items added to the listbox. Only the items that were there on page_load are displayed. How do i accomplish what i want to do

Edit 1

My Code Is like this

 protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            if (ViewState["gameID"] == null)
            {
                //Populate Listbox
                //Set gameid in viewstate
            }

            //Add javascript handlers to buttons
            btnSomeButton.Attributes.Add("onclick", "aJavaScriptFunction"); 

        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ListItemCollection x = ListBoxRanks.Items;
        //Here items is has just those items that are added to the listbox on page load

    }
+1  A: 

Only bind to the ListBox if Page.IsPostBack is false. This will allow you to see any items added on the client side.

If you are binding to the control on each load you are wiping out any existing items that were loaded by ASP.NET from the request. By only binding if the current page load was not triggered by a postback you are allowing all the items from the request to load, including any items added client-side.

Andrew Hare
This didnt work. See edit 1
Midhat
+2  A: 

Ah when abstractions leek :)

Web server controls are serialised to view state before the response is sent, the control is recreated on postback and the options all put back from view state.

When you add option items client side they are not added to viewstate. The only way is to use your own hidden field to serialise client side additions and read them on postback or ajax the additions serverside.

HollyStyles
WebForms are easy to use, but not designed to be used this way. +1
ichiban
hidden field did the trick. btw is there any difference between input type=hidden and asp:textbox style=display:none
Midhat
Nothing of great significance. input type=hidden is designed to never be displayed so is preferable from a rendering overhead point of view. Always validate the input of hidden fields serverside just like all other controls. It's slightly more work to put malicious input in a hidden field than a display:none textbox but not by much.
HollyStyles
A: 

You should use ajax to add items to the dropdown list. It will ensure your viewstate is in sync with the serverside dropdown control.

Sergiu
actually this was a server side ajax page, but we wanted something faster. so i rebuilt it all clientside today
Midhat