473,569 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP .NET 2.0 and JavaScript / JS - Select Options disappear

Hi,

I have an ASP .NET page with codebehind in a vb file.
The page has a dropdown control, and a JS function which used HTTP XML
Request to get the data from the database, and populate the dropdown.
Actually, the JS creates the OPTION elements using th retrieved db data, and
adds them to the SELECT element using DOM objects.

The dropdown works ok, and the items are visible, but when the user clicks
"Save" button, and the page posts back to the server, in the VB codebehind,
the selected value in the dropdown is empty, and the items collection is
empty.

Why is this? How can I fix this behavior?

Thanks in advance,

Richard
Jun 27 '08 #1
4 1586
Hi Richard,

The problem is that ASP maintains state by using ViewState. When you
post back a page, controls are first instantiated, then initialized
with values from ViewState, and at the very end, the SaveViewState
event is called. The next time you post back, the values that were
saved in the SaveViewState event will again be used to repopulate the
controls on Initialization.

When you modify controls like Dropdowns through Javascript (modify as
in add members, not changing the selected index), the server cannot
possibly know about this.

In your case, I would suggest you use the internal __doPostBack
Javscript function. You can check out the source of any aspx page in
your browser, and will find it there:

function __doPostBack(ev entTarget, eventArgument) {
....
}

You also need your page to implement IPostBackEventH andler to handle
the async postback. An example follows:

aspx page:

<%@ Page Language="C#" AutoEventWireup ="True"
CodeBehind="Def ault.aspx.cs"
Inherits="Imple mentIPostBackEv entHandler._Def ault"
EnableViewState ="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<script>
function populateListBox () {
var lst = document.getEle mentById('theLi stBox');
var postBackArg = new Array()
for(var i = 1;i <= 3;i++) {
var newOptionName = "element_" + i;
var newOptionValue = i;
var newOption = new Option(newOptio nName,
newOptionValue) ;
lst.options.add (newOption);
postBackArg[i-1] = newOptionName + "," +
newOptionValue;
}
__doPostBack('< %= this.ClientID %>',
postBackArg.joi n(";"));
}
</script>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="theListBox " runat="server" />
<input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
OnClick="popula teListBox()" />
<asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
Text="btnPostBa ck" runat="server" />
</div>
</form>
</body>
</html>
codebehind file:
using System;
using System.Collecti ons;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ImplementIPostB ackEventHandler
{
public partial class _Default : System.Web.UI.P age,
IPostBackEventH andler
{
protected void Page_Load(objec t sender, EventArgs e)
{
}

protected void btnPostBack_Cli ck(object sender, EventArgs e)
{
foreach(ListIte m li in theListBox.Item s)
{
/* ... */
}
}

public void RaisePostBackEv ent(string eventArg)
{
string[] newElements = eventArg.Split( ';');
foreach(string newElement in newElements)
{
string[] newElementArray = newElement.Spli t(',');
theListBox.Item s.Add(new ListItem(newEle mentArray[0],
newElementArray[1]));
}
}
}
}

=============== =
Regards,
Steve
www.stkomp.com

Richard wrote:
Hi,

I have an ASP .NET page with codebehind in a vb file.
The page has a dropdown control, and a JS function which used HTTP XML
Request to get the data from the database, and populate the dropdown.
Actually, the JS creates the OPTION elements using th retrieved db data, and
adds them to the SELECT element using DOM objects.

The dropdown works ok, and the items are visible, but when the user clicks
"Save" button, and the page posts back to the server, in the VB codebehind,
the selected value in the dropdown is empty, and the items collection is
empty.

Why is this? How can I fix this behavior?

Thanks in advance,

Richard
Jun 27 '08 #2
Thanks Steve, great explanation.
It'd be nice in JS to have a function to add objects to the viewstate ;-)

As I'm using vb in the codebehind, is it necessary to have in the code
behind page in its own namespace with the following code you posted?

namespace ImplementIPostB ackEventHandler
{
....
}

Thanks in advance,

Richard

"wi*****@google mail.com" wrote:
Hi Richard,

The problem is that ASP maintains state by using ViewState. When you
post back a page, controls are first instantiated, then initialized
with values from ViewState, and at the very end, the SaveViewState
event is called. The next time you post back, the values that were
saved in the SaveViewState event will again be used to repopulate the
controls on Initialization.

When you modify controls like Dropdowns through Javascript (modify as
in add members, not changing the selected index), the server cannot
possibly know about this.

In your case, I would suggest you use the internal __doPostBack
Javscript function. You can check out the source of any aspx page in
your browser, and will find it there:

function __doPostBack(ev entTarget, eventArgument) {
....
}

You also need your page to implement IPostBackEventH andler to handle
the async postback. An example follows:

aspx page:

<%@ Page Language="C#" AutoEventWireup ="True"
CodeBehind="Def ault.aspx.cs"
Inherits="Imple mentIPostBackEv entHandler._Def ault"
EnableViewState ="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<script>
function populateListBox () {
var lst = document.getEle mentById('theLi stBox');
var postBackArg = new Array()
for(var i = 1;i <= 3;i++) {
var newOptionName = "element_" + i;
var newOptionValue = i;
var newOption = new Option(newOptio nName,
newOptionValue) ;
lst.options.add (newOption);
postBackArg[i-1] = newOptionName + "," +
newOptionValue;
}
__doPostBack('< %= this.ClientID %>',
postBackArg.joi n(";"));
}
</script>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="theListBox " runat="server" />
<input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
OnClick="popula teListBox()" />
<asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
Text="btnPostBa ck" runat="server" />
</div>
</form>
</body>
</html>
codebehind file:
using System;
using System.Collecti ons;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ImplementIPostB ackEventHandler
{
public partial class _Default : System.Web.UI.P age,
IPostBackEventH andler
{
protected void Page_Load(objec t sender, EventArgs e)
{
}

protected void btnPostBack_Cli ck(object sender, EventArgs e)
{
foreach(ListIte m li in theListBox.Item s)
{
/* ... */
}
}

public void RaisePostBackEv ent(string eventArg)
{
string[] newElements = eventArg.Split( ';');
foreach(string newElement in newElements)
{
string[] newElementArray = newElement.Spli t(',');
theListBox.Item s.Add(new ListItem(newEle mentArray[0],
newElementArray[1]));
}
}
}
}

=============== =
Regards,
Steve
www.stkomp.com

Richard wrote:
Hi,

I have an ASP .NET page with codebehind in a vb file.
The page has a dropdown control, and a JS function which used HTTP XML
Request to get the data from the database, and populate the dropdown.
Actually, the JS creates the OPTION elements using th retrieved db data, and
adds them to the SELECT element using DOM objects.

The dropdown works ok, and the items are visible, but when the user clicks
"Save" button, and the page posts back to the server, in the VB codebehind,
the selected value in the dropdown is empty, and the items collection is
empty.

Why is this? How can I fix this behavior?

Thanks in advance,

Richard
Jun 27 '08 #3
Hi Richard,

No, the namespace was automatically generated by VS. No need for it.
Just make sure that the Inherits directive in the aspx file will not
have a namespace either (eg, Inherits="_Defa ult" instead of
Inherits="Imple mentIPostBackEv entHandler._Def ault")

===========
Regards,
Steve
www.stkomp.com

Richard wrote:
Thanks Steve, great explanation.
It'd be nice in JS to have a function to add objects to the viewstate ;-)

As I'm using vb in the codebehind, is it necessary to have in the code
behind page in its own namespace with the following code you posted?

namespace ImplementIPostB ackEventHandler
{
...
}

Thanks in advance,

Richard

"wi*****@google mail.com" wrote:
Hi Richard,

The problem is that ASP maintains state by using ViewState. When you
post back a page, controls are first instantiated, then initialized
with values from ViewState, and at the very end, the SaveViewState
event is called. The next time you post back, the values that were
saved in the SaveViewState event will again be used to repopulate the
controls on Initialization.

When you modify controls like Dropdowns through Javascript (modify as
in add members, not changing the selected index), the server cannot
possibly know about this.

In your case, I would suggest you use the internal __doPostBack
Javscript function. You can check out the source of any aspx page in
your browser, and will find it there:

function __doPostBack(ev entTarget, eventArgument) {
....
}

You also need your page to implement IPostBackEventH andler to handle
the async postback. An example follows:

aspx page:

<%@ Page Language="C#" AutoEventWireup ="True"
CodeBehind="Def ault.aspx.cs"
Inherits="Imple mentIPostBackEv entHandler._Def ault"
EnableViewState ="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<script>
function populateListBox () {
var lst = document.getEle mentById('theLi stBox');
var postBackArg = new Array()
for(var i = 1;i <= 3;i++) {
var newOptionName = "element_" + i;
var newOptionValue = i;
var newOption = new Option(newOptio nName,
newOptionValue) ;
lst.options.add (newOption);
postBackArg[i-1] = newOptionName + "," +
newOptionValue;
}
__doPostBack('< %= this.ClientID %>',
postBackArg.joi n(";"));
}
</script>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="theListBox " runat="server" />
<input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
OnClick="popula teListBox()" />
<asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
Text="btnPostBa ck" runat="server" />
</div>
</form>
</body>
</html>
codebehind file:
using System;
using System.Collecti ons;
using System.Web.UI;
using System.Web.UI.W ebControls;

namespace ImplementIPostB ackEventHandler
{
public partial class _Default : System.Web.UI.P age,
IPostBackEventH andler
{
protected void Page_Load(objec t sender, EventArgs e)
{
}

protected void btnPostBack_Cli ck(object sender, EventArgs e)
{
foreach(ListIte m li in theListBox.Item s)
{
/* ... */
}
}

public void RaisePostBackEv ent(string eventArg)
{
string[] newElements = eventArg.Split( ';');
foreach(string newElement in newElements)
{
string[] newElementArray = newElement.Spli t(',');
theListBox.Item s.Add(new ListItem(newEle mentArray[0],
newElementArray[1]));
}
}
}
}

=============== =
Regards,
Steve
www.stkomp.com

Richard wrote:
Hi,
>
I have an ASP .NET page with codebehind in a vb file.
The page has a dropdown control, and a JS function which used HTTP XML
Request to get the data from the database, and populate the dropdown.
Actually, the JS creates the OPTION elements using th retrieved db data, and
adds them to the SELECT element using DOM objects.
>
The dropdown works ok, and the items are visible, but when the user clicks
"Save" button, and the page posts back to the server, in the VB codebehind,
the selected value in the dropdown is empty, and the items collection is
empty.
>
Why is this? How can I fix this behavior?
>
Thanks in advance,
>
Richard
Jun 27 '08 #4
Hello,

Steve, I really appreciate your help with this, and I know this example is a
very sophisticated code.

Now, somehow sending data in strings around, seems like the only solution in
Web applications!?? , but it doesn't seem like a very good practice.

1) A dropdown could have many items with fairly long descriptions. If the
resulting string overflows the string size, we'd end up with a truncated
dropdown or an invalid string that cannot be parsed back into a dropdown.

2) With a string, its's hard to store state like "disabled" and other
members of the dropdown.

Seriously , isn't there a "best practice" kindof way of doing this?

Thanks in advance,

Richard
=====
"wi*****@google mail.com" wrote:
Hi Richard,

No, the namespace was automatically generated by VS. No need for it.
Just make sure that the Inherits directive in the aspx file will not
have a namespace either (eg, Inherits="_Defa ult" instead of
Inherits="Imple mentIPostBackEv entHandler._Def ault")

===========
Regards,
Steve
www.stkomp.com

Richard wrote:
Thanks Steve, great explanation.
It'd be nice in JS to have a function to add objects to the viewstate ;-)

As I'm using vb in the codebehind, is it necessary to have in the code
behind page in its own namespace with the following code you posted?

namespace ImplementIPostB ackEventHandler
{
...
}

Thanks in advance,

Richard

"wi*****@google mail.com" wrote:
Hi Richard,
>
The problem is that ASP maintains state by using ViewState. When you
post back a page, controls are first instantiated, then initialized
with values from ViewState, and at the very end, the SaveViewState
event is called. The next time you post back, the values that were
saved in the SaveViewState event will again be used to repopulate the
controls on Initialization.
>
When you modify controls like Dropdowns through Javascript (modify as
in add members, not changing the selected index), the server cannot
possibly know about this.
>
In your case, I would suggest you use the internal __doPostBack
Javscript function. You can check out the source of any aspx page in
your browser, and will find it there:
>
function __doPostBack(ev entTarget, eventArgument) {
....
}
>
You also need your page to implement IPostBackEventH andler to handle
the async postback. An example follows:
>
aspx page:
>
<%@ Page Language="C#" AutoEventWireup ="True"
CodeBehind="Def ault.aspx.cs"
Inherits="Imple mentIPostBackEv entHandler._Def ault"
EnableViewState ="false" %>
>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<script>
function populateListBox () {
var lst = document.getEle mentById('theLi stBox');
var postBackArg = new Array()
for(var i = 1;i <= 3;i++) {
var newOptionName = "element_" + i;
var newOptionValue = i;
var newOption = new Option(newOptio nName,
newOptionValue) ;
lst.options.add (newOption);
postBackArg[i-1] = newOptionName + "," +
newOptionValue;
}
__doPostBack('< %= this.ClientID %>',
postBackArg.joi n(";"));
}
</script>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="theListBox " runat="server" />
<input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
OnClick="popula teListBox()" />
<asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
Text="btnPostBa ck" runat="server" />
</div>
</form>
</body>
</html>
>
>
codebehind file:
using System;
using System.Collecti ons;
using System.Web.UI;
using System.Web.UI.W ebControls;
>
namespace ImplementIPostB ackEventHandler
{
public partial class _Default : System.Web.UI.P age,
IPostBackEventH andler
{
protected void Page_Load(objec t sender, EventArgs e)
{
}
>
protected void btnPostBack_Cli ck(object sender, EventArgs e)
{
foreach(ListIte m li in theListBox.Item s)
{
/* ... */
}
}
>
public void RaisePostBackEv ent(string eventArg)
{
string[] newElements = eventArg.Split( ';');
foreach(string newElement in newElements)
{
string[] newElementArray = newElement.Spli t(',');
theListBox.Item s.Add(new ListItem(newEle mentArray[0],
newElementArray[1]));
}
}
}
}
>
=============== =
Regards,
Steve
www.stkomp.com
>
Richard wrote:
Hi,

I have an ASP .NET page with codebehind in a vb file.
The page has a dropdown control, and a JS function which used HTTP XML
Request to get the data from the database, and populate the dropdown.
Actually, the JS creates the OPTION elements using th retrieved db data, and
adds them to the SELECT element using DOM objects.

The dropdown works ok, and the items are visible, but when the user clicks
"Save" button, and the page posts back to the server, in the VB codebehind,
the selected value in the dropdown is empty, and the items collection is
empty.

Why is this? How can I fix this behavior?

Thanks in advance,

Richard
>
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
6522
by: Kevin Lyons | last post by:
Hello, I am trying to get my select options (courses) passed correctly from the following URL: http://www.dslextreme.com/users/kevinlyons/selectBoxes.html I am having difficulty getting the courses to pass the correct option value and then be displayed at the following URL: http://www.dslextreme.com/users/kevinlyons/selectResults.html ...
1
6073
by: bin_P19 P | last post by:
the code i have got is as follows and now im stuck <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Shopping Cart</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link rel="StyleSheet" href="css/style.css" type="text/css">
9
2161
by: beguigne | last post by:
Below is a snippet of a crude date picking routine for a form. I am a novice at this so, I am hitting my head at why when I select the day, the onChange event gives me a blank. What am I missing? Regards, <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>
2
5209
by: BrianP | last post by:
Hi, I have had to invent a work-around to get past what looks like a JavaScript bug, the malfunctioning Perl-like JavaScript array functions including SPLICE() and UNSHIFT(). I have boiled it down to a very simple test case which can be cut-n-pasted into a .html file and viewed in a browser: ...
13
18664
by: monomaniac21 | last post by:
hi i want to be able to trigger a javascript style popup alert in php (i want a message displayed on the actual page) is this possible?
4
2810
by: Adam Smith | last post by:
Hello, How can I call or trigger an external javascript twice in a form? I have <script language="JavaScript" src="country_state.js" name="Country_State"> <script type="text/javascript" src="country_state.js"> </script>
9
51973
chunk1978
by: chunk1978 | last post by:
hey everyone, i've been trying to solve this problem for 2 days straight, with no end in sight. i would greatly appreciate anyone's help. EXPLANATION: There are 3 Select Menus. The 1st and 2nd Select Menu are "printing options" for 4x6 and 5x7 prints respectively. the 3rd Select Menu holds an "Email" option that can be toggled...
4
1684
by: JLupear | last post by:
My friend and I are trying to start a business and are writing a website of our own. We have been trying to create an online estimator and are having trouble with writing the javascript that is to handle the form data. I am having trouble capturing the form data for use using the onsubmit operator. We have written all of the options using list...
0
7922
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8119
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7668
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5218
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.