Using Javascript to Detect When a User Selected an Item in an ASP.NET List

I am developing an ASP.NET web application that includes google maps. I have an ASP.NET list on my page that contains a list of items. When the user selects one of the elements, I would like to show this element on the map. The main difficulty is that google maps use javascript to manage it, and listbox is a server-side control.

I can come up with two ways to do this. The first will include a list that calls the javascript function when the user selects a new item. Then I can write this function to perform the necessary operations with the cards. Unfortunately, the OnSelectedIndexChanged property in the list does not support javascript functions.

The second includes wrapping the UpdatePanel around the list and getting the list to perform the postback. In the SelectedIndexChanged event in VB / C #, I would like to somehow make a call to the javascript function, which would then update the map.

Which solution can i use?

thanks

- Amr

+4
source share
3 answers

In your code (in your pageload), just add the javascript handler to the OnChange attribute, which points to your javascript function. For instance:

 lbYourListBox.Attributes.Add("onChange", "UpdateYourMap();"); 

You can also add this to your control using the built-in javascript, but I prefer to do this in the code so that the structure can handle matching names.

+3
source

You can simply insert javascript into your page, avoiding using ASP with it. Put the code in the body of the document:

 <script language="javascript"> body.onload=function(){ var lb=document.getElementById("yourlistboxid"); lb.onChange = function(){ // put your handling code here } } </script> 
+2
source

to demonstrate a different approach here is a rough guide:

 void listbox_SelectedIndexChanged( ... ) { string js = string.Format("callToMapsFunction({0});", listbox.SelectedValue); string scriptKey = "mapscript"; ScriptManager.RegisterStartupScript( listbox, typeof(ListBox), scriptKey , js, true); } 

RegisterStartupScript runs any javascript that you provide to it after the partial postback has completed. you don’t have to pass the value of the list - only any data you want to provide to the api cards. the first 3 elements are designed to prevent the script from registering the number of times (as far as I know). true at the end tells the scriptmanager to automatically add opening and closing tags around your js code.

+1
source

Source: https://habr.com/ru/post/1304287/


All Articles