Persist ListItems added to ListBox/ComboBox etc. via JavaScript in ASP.NET

I’m sure you might have faced this problem or might have seen people asking this on various forums.

The Problem

Usually if you add any ListItem to an asp.net ListBox using any client-side code like Javascript etc., they are lost on postback. There is no inbuilt way to persist those values, because they are overwritten by the viewstate on postback.

The Solution

There’s no good solution to it. But this is how I usually do it. I have used a ListBox in this example, but would work for any other control too.

Add this javascript function to the aspx page:

<script type="text/javascript">
    //Select all ListItems in the ListBox
    function SelectAllListItems(Ctl) {
        var listbox = document.getElementById(Ctl);
        if (listbox == null) return false;
        for (var i = 0; i <= listbox.length - 1; i++) {
            listbox.options[i].selected = true;
        }
        return false;
    }
</script>

Modify your server side code in the following manner:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If IsPostBack Then ResyncAllListBoxes()
    Me.Form.Attributes.Add("onsubmit", "SelectAllListItems('MyListBox');")
    '----------------------
 
    '.......Your other Page_Load code goes here.....
 
End Sub
 
Private Sub ResyncAllListBoxes()
    MyListBox.Items.Clear()
    If Request("MyListBox") <> "" Then
        Dim MyListItems As String = Request("MyListBox")
        ' You will get a string with all ListItems seperated by comma in MyListItems
        ' Split the string and fill the ListBox again here.
 
        ' You already know the code, don't you 🙂
 
    End If
 
    '** Repeat for all such listboxes **
 
End Sub

Run the code and see how it works.

Enjoy
Hot

How This Works

ListItems added to listbox, dropdowns etc. are not recoginzed by the server side code. The server side seems to trust the ViewState more than javascript; and there’s no way to easily modify the ViewState. Fortunately the “Request” object still has the values. It still works the same way it used to in classic ASP. So what we do here is empty the listbox and fill it again from that “Request” object on PostBack.

Advertisements

2 Responses to “Persist ListItems added to ListBox/ComboBox etc. via JavaScript in ASP.NET”

  1. oppodereibfoB Says:

    nice. It helped 🙂

  2. Jose Alberto Says:

    It help me a Lot! thanks


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: