Call client side script from code behind

Hi there,

I'm trying to add two listboxes to a page so a user can move items between the lists. I need to create these list boxes in the code, as different listboxes appear for different users. The problem I'm having is that once I move the listbox creation to the code behind, I can't seem to get it to call the client side move function.

 Here's me code (lines 13 and 20 contain the call to the javascript function that I'm getting wrong):

  

1    TableRow tableRow = new TableRow();
2    TableCell lb1tableCell = new TableCell();
3    lb1tableCell.Text = "Include:";
4    ListBox listBox1 = new ListBox();
5    listBox1.SelectionMode = ListSelectionMode.Multiple;
6    listBox1.Height = Unit.Pixel(120);
7    listBox1.Width = Unit.Pixel(100);
8    
9    TableCell btnsCell = new TableCell();
10   
11   Button addButton = new Button();
12   addButton.ID = "addButton";
13   addButton.Attributes.Add("OnClick", "Javascript:MoveItem('<%= listBox1.ClientID %>', '<%= listBox2.ClientID %>');");
14   
15   btnsCell.Controls.Add(addButton);
16   btnsCell.Text = "&lt;br>";
17   
18   Button removeButton = new Button();
19   removeButton.ID = "removeButton";
20   removeButton.Attributes.Add("OnClick", "Javascript:MoveItem('<%= listBox2.ClientID %>', '<%= listBox1.ClientID %>');");
21   
22   btnsCell.Controls.Add(removeButton);
23   
24   TableCell lb2tableCell = new TableCell();
25   lb2tableCell.Text = "Exclude:";
26   ListBox listBox2 = new ListBox();
27   listBox2.SelectionMode = ListSelectionMode.Multiple;
28   listBox2.Height = Unit.Pixel(120);
29   listBox2.Width = Unit.Pixel(100);
30   
31   ListItem item1 = new ListItem();
32   item1.Value = "val1";
33   item1.Text = "Text 1";
34   listBox1.Items.Add(item1);
35   
36   lb1tableCell.Controls.Add(listBox1);
37   tableRow.Controls.Add(lb1tableCell);
38   
39   lb2tableCell.Controls.Add(listBox2);
40   tableRow.Controls.Add(lb2tableCell);
41   
42   tableRow.Controls.Add(btnsCell);
43   
44   optionsHTMLTable.Controls.Add(tableRow);
 

 Here's my client side function:

1    function MoveItem(ctrlSource, ctrlTarget) {
2        var Source = document.getElementById(ctrlSource);
3        var Target = document.getElementById(ctrlTarget);
4        
5        alert('Source: ' + Source); 
6    	alert('Target: ' + Target); 
7    
8        if ((Source != null) && (Target != null)) {
9            while ( Source.options.selectedIndex >= 0 ) {
10               var newOption = new Option(); // Create a new instance of ListItem
11               newOption.text = Source.options[Source.options.selectedIndex].text;
12               newOption.value = Source.options[Source.options.selectedIndex].value;
13               
14               Target.options[Target.length] = newOption; //Append the item in Target
15               Source.remove(Source.options.selectedIndex);  //Remove the item from Source
16           }
17       }
18      
19   }
 
0
Den21
4/15/2008 8:05:54 AM
asp.net.client-side 24353 articles. 2 followers. Follow

14 Replies
1329 Views

Similar Articles

[PageSpeed] 26
Get it on Google Play
Get it on Apple App Store

Hi,

Since you are creating dynamic controls then you need to place the code in an event which is on or before page load, so you can't create dynamic controls on a button click event because this event occures after Page_Load event.

Plus you need to recreate the controls on every post back.

Regards


Don't forget to click (Mark as Answer) on the post that helped to solve your problem.
0
mr
4/15/2008 9:14:39 AM

Will you always have the same Listbox setup for all users and only the contents will be different for the different users?

0
blobfield
4/15/2008 3:19:34 PM

Basically I'm creating an administration area for a client to manage their products. Each product can have one or more product options. For example, colour and size. The idea is that the administrator can choose which options to include, then they can select which items to have for each option. So you could choose to have a colour option. This would bring up two list boxes, one with the default list of colours, the other for the administrator to add unwanted colour options to.

 I hope this explains things a bit better!

 

0
Den21
4/16/2008 10:01:46 AM

13   addButton.Attributes.Add("OnClick", "Javascript:MoveItem('<%= listBox1.ClientID %>', '<%= listBox2

 

 

try "OnClick", "Javascript:MoveItem('alert()' ...... to see if it really call that,

0
j4m35bond
4/16/2008 10:35:21 AM
Adding this didn't work: 

addButton.Attributes.Add("OnClick", "Javascript:MoveItem('alert()')");

If I add an alert to the client side javascript function that works. So it's calling the function, but not passing the values I need.

0
Den21
4/16/2008 10:59:32 AM

I just thought of something quite vital, I'm using a master page. Could this be why I'm struggling to get the value of a dynamic control?

0
Den21
4/17/2008 11:43:12 AM

Since you're now adding the onclick event to your buttons in the code-behind, this line:

addButton.Attributes.Add("OnClick", "Javascript:MoveItem('<%= listBox1.ClientID %>', '<%= listBox2.ClientID %>');");
is just going to render as something like this on the client, which I assume is not your intention:
<input type="submit" name="addButton" value="HELLO" onclick="Javascript:MoveItem('&lt;%= listBox1.ClientID %>', '&lt;%= listBox2.ClientID %>');" id="addButton" />
 You need to update it to something like this instead:
addButton.Attributes.Add("OnClick", "Javascript:MoveItem('" + listBox1.ClientID + "', '" + listBox2.ClientID + "');"); 
You'll also need to reorder your lines a bit so this line is executed after the creation of listBox2. I also think you need to assign IDs to listBox1 and listBox2 in the code.

"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
4/17/2008 11:58:21 AM

You're a star!!! I made your changes and it worked, I think the main thing was not assigning an ID to the control which makes perfect sense!

Thanks so much!! ...just one more thing, any idea how to stop it doing the postback after calling the javascript function? The item moves over to the right list box, but then post back so the original list appears.

0
Den21
4/17/2008 12:34:31 PM

Sure, add return false; to the end of the button onclick and this should cancel the postback:

addButton.Attributes.Add("OnClick", "Javascript:MoveItem('" + listBox1.ClientID + "', '" + listBox2.ClientID + "'); return false;"); 

 


"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
4/17/2008 12:38:27 PM

Thanks, sorry, that was pretty thick of me. I've been puzzling over this problem for far too long!

 

Thanks again for your help Big Smile

0
Den21
4/17/2008 12:43:06 PM

Arghhhh!! Can't believe it! I got it all working in a test page, when I've added it to my project under the master page it doesn't work!! Any ideas..?

 The code is rendered like this:

 <table id="ctl00_ContentPlaceHolder1_optionsTest" border="0">
<tr>
<td>Include:<br>
<select size="4" name="ctl00$ContentPlaceHolder1$testBox1" multiple="multiple" id="ctl00_ContentPlaceHolder1_testBox1" style="height:120px;width:100px;">
<option value="val1">Text 1</option>
</select>
</td>
<td>
<input type="submit" name="ctl00$ContentPlaceHolder1$addButton" value="add" onclick="Javascript:MoveItem('testBox1', 'testBox2'); return false;" id="ctl00_ContentPlaceHolder1_addButton" />
<input type="submit" name="ctl00$ContentPlaceHolder1$removeButton" value="remove" onclick="Javascript:MoveItem('testBox2', 'testBox1'); return false;" id="ctl00_ContentPlaceHolder1_removeButton" />
</td>
<td>Exclude:<br>
<select size="4" name="ctl00$ContentPlaceHolder1$testBox2" multiple="multiple" id="ctl00_ContentPlaceHolder1_testBox2" style="height:120px;width:100px;"></select>
</td>
</tr>
</table>

0
Den21
4/17/2008 1:01:43 PM

Don't panic! Smile

It's to do with the naming containers and ClientIDs of your dynamic controls. At the moment they're rendering the onclick as Javascript:MoveItem('testBox1', 'testBox2'); return false;"  which is fine until you move your code into a MasterPage where your listboxes are given different ClientIDs, e.g. ctl00_ContentPlaceHolder1_testBox1. It turns out the order of execution of those lines of code is all-important. Move the lines where you add the onclick to your button to after you've added your dynamic controls to the page, that way the ClientIDs you get in your code-behind reflect the final ClientID they will be given as ASP.Net knows where they're going to go.

I hope that makes sense.
 


"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
4/17/2008 1:25:12 PM

Ah, I see, again that makes sense. I thought once I'd added the control to the cell that would be ok, but it seems it only assigns the id once the row is added. I'll re jig my layout.

 Panic over! Thanks again for you invaluable help!

0
Den21
4/17/2008 1:42:11 PM
No worries, I hope it works. I didn't spot that issue straight away but I suppose it makes sense - until ASP.NET knows where your control is going in the overall control hierarchy it can't give you the *final* ClientID.

"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
4/17/2008 1:50:43 PM
Reply:

Web resources about - Call client side script from code behind - asp.net.client-side

MUD client - Wikipedia, the free encyclopedia
A MUD client is a computer application used to connect to a MUD , a type of multiplayer online game . Generally, a MUD client is a very basic ...

3Q Digital Offers Peek At 3Q Facebook Ad Performance By Its Largest Clients
With Facebook set to report its third-quarter earnings Wednesday , digital marketing agency 3Q Digital offered some insight on how the social ...

Gallop Labs hires former Facebook Client Partner as Director of Sales
Gallop Labs , a social marketing and analytics firm, announced that it has hired former Facebook Client Partner Andrew Peebles as the company’s ...

Lawyer labels client 'stupid' after New Year text to ex lands him behind bars for a week
Man's five days in prison for New Year text was significant &quot;wake-up call&quot;, lawyer says.


The 2015 Awards Report: See the World's Most Creative Agencies, Campaigns and Clients
We present the winners of our 2015 Awards Report, highlighting the most creatively celebrated companies and personalities of the year. As you'll ...

Anchorage Assembly candidate drops out rather than reveal tutoring clients
... Anchorage Budget Advisory Commission, has withdrawn a bid for the Assembly because she did not want to list the names and addresses of clients ...

Spotlight On NW Creative: Fell Swoop And Its Unique Client Mix
After living in Seattle for a few years, it’s become clear to me that many shops here struggle to capture significant business from clients headquartered ...

New online FX broker group rails against client money laws
A group of online broking firms have launched a desperate bid to sway the government on its proposed client fund segregation laws.

SanDisk Announces X400 Client SSD for OEMs
... Like the X300, the X400 uses TLC NAND flash and relies on SLC-mode write caching to provide competitive write speeds. SanDisk OEM Client SSD ...

Resources last updated: 1/11/2016 9:42:04 PM