Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I manipulate ASP.Net server controls with script code

Status
Not open for further replies.

JCruz063

Programmer
Joined
Feb 21, 2003
Messages
716
Location
US
Hi All,
This is driving me insane. People please help me out!

(I'm working with ASP.Net using C#)
I need to manipulate a couple of server-side controls (CheckBox, DropDownList, ListBox, etc) using client-side script. The problem is that the object model of the server-side controls is not accessible via client-side script. For example, in a code-behind class, I could write:
Code:
   //This is C# code
   DropDownList ddl = new DropDownList();
   ddl.Items.Add(...);
In client-side script, however, the story is different. If I were to write the same code I wrote above, I would get an error in the page. So, the question is: How do I interact with server-side controls using client-side script?

Please note that this problem has reached very high frustration levels and that lack of help would cause me to commit suicide (ok, ok, maybe I won't - just help me out)

Thanks!

Jose
 
Since all server side controls produce an HTML control(i.e. DropDownList=<select>, ListBox=<select multiple>, CheckBox=<input type=checkbox>), you can as well execute client side javascript, attached to an event of this HTML controls. Here is a sample:
Code:
<html>
<head>
 <script language=javascript>
  function showSelected(ddl){
   alert(ddl.options[ddl.selectedIndex].text);
  }
 </script>
</head>
<body>
 <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;>
   <asp:DropDownList id=DropDownList1 runat=&quot;server&quot; />
 </form>
</body>
</html>
code behind:
protected System.Web.UI.WebControls.LinkButton LinkButton1;
	
private void Page_Load(object sender, System.EventArgs e)
{
 if(!Page.IsPostBack)
 {
  for(int i=0;i<5;i++)
  {
   ListItem li = new ListItem(&quot;Item &quot;+i.ToString(), i.ToString());				  
   DropDownList1.Items.Add(li);
  }
}

override protected void OnInit(EventArgs e)
{
  //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
  InitializeComponent();
  base.OnInit(e);

  if(DropDownList1.Attributes[&quot;onchange&quot;] == null)
  {
    DropDownList1.Attributes.Add(&quot;onchange&quot;, &quot;javascript:showSelected(this);&quot;);
  }
}
You got the general idea. In the same manner you would execute a client side &quot;onclick&quot; event for a Button control(<input type=button>).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top