views:

155

answers:

3

I am trying to replace postbacks with javascript client side processing whenever I can in my aspnet c# 3.5 code so as to improve the user experience. I am not using any javascript frameworks. I am using vs2008.

I have a usercontrol .ascx file with a dropdown list and button which is used in three places on my main screen.

I had been doing a postback on OnSelectedIndexChanged for the dropdown list.

I don’t need to postback every time though, so I tried putting in a javascript function in the usercontrol to check the item selected and only do a postback if it starts with ‘-‘.

However the name of the elements I need to $get in my javascript function depend on the name of the usercontrol instance which calls it, and I need to get that name at runtime, for example : uc1_ ddlLocations and uc1_ btnPostBack.

Here is the code:

<script type="text/javascript" language="javascript">
function ddlChange(this) { 
var loc = $get("GetTheUserControlNameAndInsertHere_ddlLocations"); 
if (loc.value.substring(0,1)=='-' )  
{ 
var btn = $get("GetTheUserControlNameAndInsertHere_btnPostBack ");  
btn.click(); 
}
</script>

How do I do this? Can someone suggest a better way to do what I am trying to do?

A: 

use the ClientID of you control and give it to your javascript

Gregoire
A: 

You can set the ClientID to a Javascript variable from the code behind.

Use that Variable in javascript call to get the element.

+1  A: 

You could determine the UserControl name by parsing it out of the ddl name. Please keep in mind that I didn't debug the parsing logic, it might be off slightly :)

<script type="text/javascript" language="javascript">
  function ddlChange(ddl) 
  { 

    if (ddl.value.substring(0,1)=='-' )  
    { 
      var prefixEndLoc = ddl.id.lastIndexOf("_");
      var prefix = ddl.id.subString(0,prefixEndLoc);
      var btn = $get(prefix + "_btnPostBack ");  
      btn.click(); 
    }
  }
</script>
JustLoren
Just going to add: 1. need to have: dlLocations.Attributes.Add "OnChange", "javascript:locChange(this);");in the pageload code behind to pass the javascript parm (ddl), and 2. I added an else ddl.blur(); to remove focus from the dropdownlist item selected. Would have been confusing to the user otherwise. Thanks, JustLoren!
Lill Lansey