ASP.NET can take a little getting used to, but once you have the hang of server-side events and
the distinction between code-in-front and code-behind, it's easy to get carried away with the thinking that everything needs to be a server-side event. As ever, the rule of thumb with ASP.NET is: if you think you're writing too much code, you probably are.
Here's a classic example of how you can do one thing several different ways in ASP.NET, but where they work very differently under the covers. Here are three different ways to update some text on a page from the value in a drop down menu.
- The first method uses an html "select", but sets it runat="server".
- The second example is essentially the same, but uses the built-in ASP.NET asp:DropDownMenu. This hands over the responsibility of rendering the control to ASP.NET, which will take into account the user's browser capabilities. Both of these examples do the actual text updating client side.
- The third example is a heavyweight example of what NOT to do -- use an AutoPostBack and make a full trip back to the server, just to update some text on the page. This is a waste of everyone's bandwidth, and unnecessary since everything you need is already sitting out there in the user's browser.
You can try the code out
here.
< script language="c#" runat="server" >
protected override void OnLoad(EventArgs args)
{
string[] options = {"one", "two", "three", "four"};
this.dropDownMenu1.DataSource = options;
this.dropDownMenu2.DataSource = options;
this.dropDownMenu3.DataSource = options;
//Extremely inefficient: this code makes a trip back to the
//server just to update some text in a div?
if(base.Page.IsPostBack)
{
this.myLabel.InnerHtml = this.dropDownMenu3.SelectedValue;
}
base.DataBind();
}
< script type="text/javascript" >
function updateLabel(menu)
{
//much more efficient: do the update client-side
var selectedText = menu[menu.selectedIndex].text;
document.getElementById("myLabel").innerHTML = selectedText;
}
< form contenteditable="false" id="form1" runat="server" >
All of these three drop down menus have the same options and update the same div ...
But they each do it differently. All have their datasources set server-side.
OPTION 1: An Html Control
Select: < select id="dropDownMenu1" runat="server" onchange="updateLabel(this);">
OPTION 2: An ASP.NET server-side asp:DropDownList control
Select me:< asp:DropDownList id="dropDownMenu2" runat="server" onchange="updateLabel(this);">
OPTION 3: An ASP.NET server-side control with an AutoPostBack
Select me:< asp:DropDownList id="dropDownMenu3" autopostback="true" runat="server">
< div id="myLabel" runat="server" style="font-size: 22pt; color: red;">???