This article covers a fundamental use of the .NET LinkButton web control for page postbacks.A web developer is routinely faced with the challenge of knowing which link was clicked. The typical solution involves passing information on the querystring in the clear, like this: "GetProduct.asp?ID=3762". A key benefit of the LinkButton web control is the power to know which link was clicked by using POST rather than GET. This is accomplished by setting 2 properties on the LinkButton: CommandName and CommandArgument. These properties are passed into the onCommand event when the user clicks a LinkButton. In the event handler for onCommand, the CommandName and CommandArgument properties can be evaluated in CommandEventArgs. Because this all takes place in the POST, the querystring is shorter and the postback data is hidden. Let's begin by looking at some code. First, a "mini" database of products is created in the code using two instances of System.Collection.Hashtable. One hashtable stores the ProductId and ProductTitle, and the other hashtable stores the ProductId and ProductDescription. The two Hashtables are related by the ProductId. This technique is OK for demonstration purposes; however, there are cleaner ways to accomplish this. Hashtable hashProductName = new Hashtable(); Hashtable hashProductDesc = new Hashtable();
void BuildMiniDatabase() { hashProductName[0] = "Jalapeno Dip" ; hashProductDesc[0] = "Simmered in mayonaise and wine, this Jalapeno Dip will make your eyes water" ;
hashProductName[1] = "Smoked Sausage" ; hashProductDesc[1] = "Mouth watering and delicious sausage" ;
hashProductName[2] = "Shrimp Fiesta" ; hashProductDesc[2] = "East Coast's finest shrimp" ;
hashProductName[3] = "Jerk Chicken" ; hashProductDesc[3] = "A real island experience you will not forget" ;
hashProductName[4] = "Beer-Battered Fish" ; hashProductDesc[4] = "Pabst Blue Ribbon and Fish. Wow!" ;
hashProductName[5] = "Bacon Burger" ; hashProductDesc[5] = "Big, juicy, and bursting with flavor" ;
hashProductName[6] = "Sirloin Tip" ; hashProductDesc[6] = "Delicate cuts with no fat" ;
hashProductName[7] = "Baked Alaska" ; hashProductDesc[7] = "Fine dessert comprised of sponge cake topped with ice cream and covered with meringue. The meringue is browned before the ice cream can melt." ;
hashProductName[8] = "Fried Chicken" ; hashProductDesc[8] = "Country cookin'" ;
hashProductName[9] = "Fresh Garden Salad" ; hashProductDesc[9] = "Crispy iceberg lettuce and a garden of vegtables" ;
hashProductName[10] = "One Pea" ; hashProductDesc[10] = "A single green pea that will leave you craving more" ;
}
Next, the web page layout is very basic. Inside a form, a table is built with 2 columns. The left side cell will hold the product links. The right cell will display the product description.
<body> <form id="MainForm" method="post" runat="server" > <asp:Table CellPadding=6 CellSpacing=2 BorderColor="#DDDDDD" BorderStyle=Solid BorderWidth=2 Runat=server> <asp:TableRow Runat=server> <asp:TableCell id=LinkList Wrap=False BackColor="#FFFFFF" Runat=server/> <asp:TableCell id="tablecellMessage" CssClass="ProductDesc" Runat=server></asp:TableCell> </asp:TableRow> </asp:Table> </form> </body>
Now that the web page is designed, the LinkButtons can be added. The LinkButtons are added dynamically using code. The System.Web.UI.WebControls.LinkButton control is instantiated and assigned to _LB1. The Text property is used for rendering the hyperlink label. That is, the text that sits between . The CommandName and CommandArgument are what's it all about. Use the CommandArgument property to specify an argument that complements the CommandName property. What might have been placed on the querystring, will now simply be assigned in the CommandName and/or CommandArgument properties. In my example, I'm really just using the CommandArgument property for storing the ProductId of each product link. The CommandName is used to identify my grouping of links which happen to be the same - they're all products. void BuildLinkList () { for (int i=1; i<=10; i++) { LinkButton _LB1 = new LinkButton(); _LB1.Text = hashProductName[i].ToString(); _LB1.CssClass = "ProductLinks"; _LB1.CommandName = "Products"; _LB1.CommandArgument = i.ToString() ;
The onCommand event is fired when a user clicks a LinkButton. Because my LinkButtons are added programatically, I need to wire the onCommand event to the control and assign it to the OnLinkClick event handler. _LB1 .Command += new System.Web.UI.WebControls.CommandEventHandler(OnLinkClick);
LinkList.Controls.Add(_LB1); LinkList.Controls.Add(new LiteralControl(" "));
When the user clicks a product link, the OnLinkClick event handler will determine which link was clicked, get the ProductId from the CommandArgument property, retrieve the ProductDescription from the mini database, and display the result on the web page. void OnLinkClick (object O, System.Web.UI.WebControls.CommandEventArgs E) { int RecordId = Int32.Parse(E.CommandArgument.ToString()); tablecellMessage.Text = "<b>" + hashProductName[RecordId].ToString() + "</b> <i>" + hashProductDesc[RecordId].ToString() + "</i>"; }
The LinkButton web control will most likely become a fundamental part of your ASP.Net programming. | DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More ASP.NET Code Articles More By Troy Karhoff developerWorks - FREE Tools! | Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools. FREE! Go There Now!
| | | | Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations. FREE! Go There Now!
| | | | CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP. FREE! Go There Now!
| | | | Download the IBM WebSphere Portal V6.1 beta code and learn more about the rich features and enhancements in IBM WebSphere Portal V6.1. WebSphere Portal provides a composite application or business mashup framework and the advanced tooling needed to build flexible, SOA-based solutions, and scalability to meet the needs of any size organization. FREE! Go There Now!
| | | | Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server. FREE! Go There Now!
| | | | Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing. FREE! Go There Now!
| | | | Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs). FREE! Go There Now!
| | | | This whitepaper provides areas to consider when evaluating any software configuration management solution. It addresses how the IBM solutions (Rational ClearCase and Rational ClearQuest) meet the needs and requirements of both project leaders and developers to provide successful Software Change and Configuration Management. FREE! Go There Now!
| | | | Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services. FREE! Go There Now!
| | | | WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |