Building ASP.NET User and Server Controls -- Part 1

By Solomon Shaffer

The introduction of .NET has led to many changes, including the way we work with forms and controls. This is especially true in the Internet realm because this environment is trying desperately to catch up with the interactive feel of traditional Windows forms-based applications.

Microsoft has taken great strides to achieve this goal with tools such as the ASP.NET ViewState and object caching. Another goal is to make the toolset to build these Internet applications very useful and broad. One of the tools that are afforded to us is ASP.NET user controls and the ability to treat these controls as actual objects within our applications. This article will explore how user controls can be practical and will lay the groundwork for building more complex controls in the future.

What Is an ASP.NET User Control?

If you have been dabbling in ASP.NET for any time, you have probably heard myriad definitions for a "user control." Why not add one more to the list? An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate a piece of functionality. A user control could simply be an extension of the functionality of an existing server control(s) (such as an image control that can be rotated or a calendar control that stores the date in a text box). Or, it could consist of several elements that work and interact together to get a job done (such as several controls grouped together that gather information about a user's previous work experience).

In either case, a user control typically resides on a page with other elements. This breakup of functionality could be the basis of an entire application built with independent and reusable user controls. The controls could then be dynamically loaded into different areas of the page. Microsoft has released the sample IBuySpy application to illustrate this architecture. The IBuySpy application can be located at www.ibuyspy.com.

With this methodology in mind, you may be asking yourself what is the difference between ASP.NET user controls and simply embedding other pages on the page? Couldn't we do that in ASP 3.0? The power comes from the framework treating the user controls as a standalone object. By exposing properties of the control through the code-behind (or in the HTML), other elements can interact with the user control programmatically and with ease. While replicating this functionality is possible in ASP 3.0, it was quite a troublesome task. Now with user controls being treated as objects, we can get and set values such as mode, size, behavior dictation, and colors with relative ease.

User Controls vs. Other Controls

One source of confusion when working with ASP.NET is knowing the difference between the many different types of controls out there and what they should be called. Microsoft has attempted to distinguish this variety, but myriad names still exist for elements that have only subtle differences. For instance, an ASP.NET control (sometimes called a server control) is a server-side component that is shipped with .NET Framework. A server control is a compiled DLL file and cannot be edited. It can, however, be manipulated through its public properties at design-time or runtime. It is possible to build a custom server control (sometimes called a custom control or composite control). (We will build these in part 2 of this article.)

In contrast, a user control will consist of previously built server controls (called constituent controls when used within a user control). It has an interface that can be completely edited and changed. It can be manipulated at design-time and runtime via properties that you are responsible for creating. While there will be a multitude of controls for every possible function built by third-party vendors for ASP.NET, they will exist in the form of compiled server controls, as mentioned above. Custom server controls may be the .NET answer to ActiveX Web controls.

Creating a Simple User Control

In this article, we will build two user controls. To cover the very basics, our first example will be an extremely simple calendar control. The control builds on the functionality of the existing ASP.NET calendar control by adding a text box to store the value selected. The calendar visibility will be toggled by a button. The user control could then be useful on a form that requires a date to be entered, but page real estate is a concern.

For clarity, both examples are written in C#, and the full source code is available below.

To create our first user control, we need to add a user-control file to a project. First, create a new C# ASP.NET Web application. Right click on the project in the Project Explorer and click Add - Add New Item and select a Web User Control item. This adds a file with the extension .ascx to the project. This is the file that the user control will use to expose its interface. An .ASCX file cannot be viewed directly in the browser. It will need to be placed within a container (such as another Web form) to be viewed. So, let's add a new Web form to the project, open it, and drag the user-control file onto the page. The following is displayed.

An ASP.NET user control is placed on a Web form
Figure 1 - An ASP.NET user control is placed on a Web form here. User controls cannot be viewed directly. They must be placed within a host, such as a Web form, to be viewed.

Notice how the control does not show any interface in the designer. This can be a problem if your control takes up any amount of space. You will have to view it in the browser to see how it looks and to make adjustments to height and width. Also notice how the page represents the control as an object. If you look at the HTML by clicking on the HTML tab, you see the following.

The user control is placed on the hosting page like any server control
Figure 2 - The user control is placed on the hosting page like any server control, only its directive is explicitly declared.

The control is represented with tags on the page, much like a server control would be. Notice the "@ Register" directive on line 2. This registers the control on the page. Once the control is registered on the page, you can freely add many instances of the controls to the page. The "TagPrefix" attribute specifies the prefix to use for the control(s). It is sort of like a namespace in which several controls might share a single prefix value. This is why all ASP.NET server controls specify the "<asp:" prefix. The only difference is that the ASP.NET server control directive is implied and not explicitly declared. The TagName specifies the name of the control. Together, the tags create an instance of the control specified at the location of the "Src" attribute. You must also include the "runat='server'" name/value pair to manipulate the user control programmatically. Otherwise, only the raw HTML is sent back to the browser.

Next, open the user-control file. It contains both an ascx file and an ascx.cs file. In the designer, drag and position a text-box server control, a button server control, and a calendar server control. As stated earlier, elements placed for use within a user control are called "constituent controls". In the HTML view, format the constituent controls as follows.

The user-control ASCX file contains HTML and server controls
Figure 3 - The user-control ASCX file contains HTML and server controls.

Notice the lack of <BODY> tags. A user control does not need these tags because it will be placed on another page (or another user control) and rendered inline. The hosting page will be responsible for these common tags. The user control will, therefore, inherit all the host tags (including styles), unless they are specified otherwise. Finally, you can add code logic to the code-behind file (ascx.cs file) as appropriate.

This is some simple C# logic in the code-behind file
Figure 4 -This is some simple C# logic in the code-behind file.

The code in the code-behind works exactly the same as a Web form. HTML will be rendered and sent to the browser exactly as if the user control's resulting HTML was simply pasted into the hosting page's markup. In this code, we are catching a button click, and the page is posting back. If the user control is placed on a page and posts back to the server, the entire page is posted back. This control is screaming for some advanced functionality, such as the ability to not post back with each button click and the ability to do text-box validation. A makeover is also in order. While this control has much to be desired, it is a good starting point and a useful example of extending the capabilities of an existing control. Let's look at a slightly more complex control, a login screen.

Creating a Slightly More Complex Control

For this example, we will create a login screen that consists of two labels, two text-box server controls, two required field-validation server controls, and a button server control. We will also expose a property or two to make it a little more versatile. After we have created a blank user control in our project, add the following.

This is thee HTML interface to the login control
Figure 5 - This is thee HTML interface to the login control. The red asterisks are required field-validation controls.

In the code-behind, add the following code.

This is the C# code in the code-behind
Figure 6 - This is the C# code in the code-behind.

The first thing to notice is that a user-control class is abstract. It must be inherited to implement its functionality. This is done by the parent page, which treats the user controls as a child object. Also, notice that the class inherits from System.Web.UI.UserControl. This gives the control the internal plumbing it needs to render itself. Most of the events and properties can be specified and overridden in your code-behind. After the control declarations, we declare two global variables. These contain the values set in the public property get and set routines. Also, be aware that the sBorderColor variable is public because we are referencing this variable in the HTML using our tried and true <% %> tags.

This demonstrates response writing the border color value into the STYLE section of the document
Figure 7 - This demonstrates response writing the border color value into the <STYLE> section of the document. Again, notice the lack of <BODY> tags.

The get and set routines
Figure 8 - The get and set routines provide a gateway to our private variables.

The get and set routines set the global variables' values. The properties of the user control can either be set in the host page HTML at design-time or in the host page code-behind at runtime.

Properties are set inline with the HTML
Figure 9 - Properties are set inline with the HTML, just like ASP.NET server controls.

Notice how the property names exposed in the get and set routines are specified in the control declaration on the hosting page. Values can be passed in here as strings. As we will see in part 2, the internal logic may be expecting a different data type, and we will have to handle that circumstance. Also, the property names are not case-sensitive if referenced in the HTML. By setting some special attributes on the class, properties may also be set as child elements on the object. To do this, set the class attribute "ParseChildrenAttribute" equal to true. This may be useful if you have a multitude of properties to set or child controls to create at runtime. The DataGrid server control and calendar server control make good use of this.

This is the routine to set the username text-box value
Figure 10 - This is the routine to set the username text-box value.

Now we set the text-box equal to the sUsername value. The event that this fires on is the OnPreRender event. This event is part of the page life cycle (which user controls consequently share), and we are overriding it to fire our code at that time. The OnPreRender event is one of the last events that fires during the creation of a page, so we are assured that the contents of the text box will not be disturbed by typical mechanisms in the ASP.NET page life cycle. If we ran this code at the Page_Load event, the contents of our text box would not remain intact because the ViewState information would clear it out. For more information on the course of a page from creation to disposal, look at my article entitled The ASP.NET Page Life Cycle. By using this functionality, we can set the username text box if we need to, as described in the code comments above.

Setting the username property is not required at all, but it is important to thoroughly test your controls with various (or no) values set in your properties. You may get unexpected results. Placeholders are set within the code above to allow you to get the username from other sources, such as a cookie or previous login. When completed, the control could be placed on any page that requires a login. Logic could be placed in the Page_Load event that will set the control's visibility property to false if the user has the required credentials. Since the control is seen as one complete object, this is done by simply making the statement, "this.visibility = false".

Conclusion

While this control is also quite simple, it lays the foundation for much more complex and innovative user controls. User controls can be very useful for breaking down a large application into smaller, more manageable chunks. In part 2 of this article, we will dive into a much more complex compiled custom, server control. We will discuss some of the issues about making the control behave correctly and emit cross-browser HTML, and adding the control to the Integration Development Environment (IDE) toolbox. Finally, we will use both of these controls' types together for some rather dramatic results.

Appreciation

I would like to thank my wife for her support through the years. I would also like to thank my colleague and friend, Joe Slovinski, for his continued help.

About the Author

Solomon Shaffer has worked in the information technology industry for more than five years. He recently founded Cynthetic, Inc., a software-development practice focused on .NET and Microsoft Internet technologies. Solomon's areas of expertise include .NET, ASP, SQL Server, COM, and UI layout/design.

At press time, Solomon is working on a contract basis in the Atlanta area building the next-generation Web applications using the .NET platform. He has over one year of enterprise .NET development experience, developing enterprise applications with the platform since its Beta 1 release as part of the Early Adopters Program. Solomon and his wife reside in Alpharetta, Georgia.



Downloads

Comments

  • comamoodimi LaXanapseBave voicioxobby 11164

    Posted by Katterarf on 06/03/2013 03:21am

    groutbarrit It’s fast and easy, and it lets you change your cheap nhl jerseyslook in seconds. groutbarrit The three-point fit keepswholesale nhl jerseysthe optics in precise alignment while dual cam hinges blend smoothly into the sculpture. groutbarrit It’s fast and easy, and it lets you change your cheap nhl jerseyslook in seconds. groutbarrit This unique oakley Batwolf sunglass has acheap mlb jerseysThree-Point Fit that keeps the _________________________________________________________________________________________________________

    Reply
  • グッチ 財布 メンズ ZHltp88Ij

    Posted by Twereerejuddy on 05/23/2013 06:52pm

    弊社はいろいろグッチ財布、グッチ 長財布、グッチバッグなどを提供いたします。 groutbarrit グッチ 店舗 最大80% OFF,グッチ 財布 メンズ バッグ 長財布 最安値価格,人気最高品質のルイ ヴィトン 財布,流行のグッチ 財布,超激安ブランド館 groutbarrit グッチ ベルト

    Reply
  • You pine on the side of some tomato basil and mozzarella. In behalf of indoor from, these slippers are as be exposed and manueverable as sneakers.

    Posted by Soaceddew on 04/19/2013 03:24am

    Has only released several chic color Subject to Inneva Woven shoes, Nike recently with another pathway to regurgitate shoes with distinguishable styling to all [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] eyes. This brings important edition Pardon Inneva Woven is a Fair-skinned Marker of works in the series, represents shoes Italian made the assurance. Latest Allowed Inneva Woven black and pornographic are available in two color schemes, to hand-knit Woven vamp in extension to infiltrated Italy's [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] finest crafts, in the meantime gives athletes close to the foot of relieve, the most important possibility a affairs is the end of Loose 5 configuration, barefoot know it resolution bring cannot be ignored. Nike Disburden Inneva Woven SP White Characterization Pack on Parade 16 at outlets about the [url=http://markwarren.org.uk/goodbuy.cfm]nike free[/url] trade name on the shelves, and on sale in restricted form, interested friends should recompense fasten ralame to Nike announced the news.

    Reply
  • http://www.nikeairmaxwr.com/ xgfpzi

    Posted by http://www.nikeairmaxwr.com/ Suttonxqq on 03/31/2013 07:16am

    Xiao Feng watching red blush, a look of panic overwhelmed look cute girl, and feeling a little frustrated, a little funny, a little comfort. Hi ... that he is still quite charming, ray ban aviators really handsome, suave a pear tree pressure Begonia looks invincible super big handsome guy wins Pan! Oh ...... ah! ray ban aviator sunglasses trouble what!ray ban wayfarer sunglasses, Xiao Feng very consciously own eyes charm due to its own charm, but also re-found self-confidence and direction.ray ban caravan, In fact, Xiao Feng did not deliberately use the ability of their eyes, this is a natural temperament distributed mind very firm talent not only his eyes.oakley sunglasses outlet, And there is the Yakumo heart is so lonely, already feel that no one will care about their world, but the sudden appearance of a concern for their own people, but also a big handsome guy, belongs to girls should nature makes her not consciously love interest in pity of Xiao.

    Reply
  • sexy adult costumes

    Posted by Fishnetzm1044 on 03/29/2013 09:58am

    http://SexyTeddies.webs.com - sexy lingerie teddiesBy signing up as an affiliate, you will be directing customers to purchase items in exchange for a commission On one of the calls he just casually mentioned that four months after installing the systems, he has not had a workmans compensation claim in two months, something that was very common before the cameras were installed http://G-string.webs.com - sexy stockingsFor example, red roses and dressIt's been said that October 31st is the one day out of the year where inhibitions can be shed and modesty can be put to the side http://cheapspicylingerie.webs.com - cheap lingerieVarious retailers, designers and vendors are offering a wide range of wholesale lingerie dresses both offline and onlineA fresh addition to the child mermaid costume collection are the Barbie Mermaid costumes http://sexycostumesus.webs.com - School Girl LingerieYou might spend a lot of time getting the perfect gift but with a wrong color?Wicked Temptations http://cheapspicylingerie.webs.com - cheap lingerieAll of them definitely offers the comfort and style that dreamgirl international has to offer Destining this costume to turn into a favorite amongst the mermaid Halloween costumes

    Reply
  • cheap sexy lingerie

    Posted by Fishnetud1028 on 03/29/2013 09:46am

    http://G-string.webs.com - G-stringIn this case, you can’t choose a gift base on his personalitys most favorite sites for placing orders on sexy lingerie http://discountsexylingerie.webs.com - Sexy Lingerie storeHowever, when you are looking for the right plus size lingerie for you, there needs to be a careful selection process to ensure that it will work for you  The upside down pear where a woman has smaller hips but wider shoulders http://Lingeriesv.webs.com - red LingerieThere are a bunch of dreamgirl lingerie retailers in the netToday, vintage baby doll lingerie can be highly valuable http://discountsexylingerie.webs.com - Chinese ManufacturerThe discount that the lingerie wholesaler offers may vary greatly ?it can be a very small discount or the discount may also, at times, be quite largeThe costume's sea colors of mostly blue-green along with some turquoise and sequin patterns will have you looking like a mesmerizing mermaid of the deep seas http://sexylingerieshops.webs.com - Trashy LingerieToday, vintage baby doll lingerie can be highly valuable If you are an eBay seller, you can sign up to be an eBay Trading Assistant or ask friends and family if they have anything they would like for you to try and sell for them

    Reply
  • Lace Babydoll

    Posted by Fishnetjb1063 on 03/29/2013 09:35am

    http://babydolllingeriee.webs.com - womens babydollAs you can see the mermaid's attraction to males is pretty influential stuff But it is always very important to make the right decision while selecting the type of baby doll lingerie http://lingeriemall.webs.com - pink lace lingerieWhen it comes to choose the right color, stick to one that compliments your look The more skin you show, the hotter it is http://sexystockings.webs.com - Body Stockings2 It can be quite sensual since it brings the body contours to proportion and this is why the sizing matters http://spicylingeries.webs.com - sexy lingerie for womenAs the middleman, you would price the items at a fair markup, collect the payment from customers and then pay the dropshipper their requested wholesale price After all, from Oct http://discounteroticlingerie.webs.com - Discounted LingerieThe child mermaid costumes, like the adult mermaid costumes, also come in a variety of sea-green-blue colors and designs), colors, and above all, size

    Reply
  • Discounted Lingerie

    Posted by Fishnettr1085 on 03/29/2013 09:02am

    http://sexycostumesa.webs.com - Naughty School Girl UniformIt is a day in which it is completely socially acceptable to don an outfit you would only dream of wearing in your wildest fantasies It offers an eye-catching assortment of lingerie in different colours, designs, and patterns to meet the requirements of different kinds of clients http://Lingeriesv.webs.com - Camouflage LingerieWhen buying sexy lingerie pick something that could get your lover excited but don’t just pick it because you want to see either your partner or you in it, pick it for your partner as you will be happier later  If she is an outgoing person then you can choose lingerie that is a little more exciting and daring http://discountsexylingerie.webs.com - Discounted LingerieThe dreamgirl lingerie international catalogue offers a list of dreamgirl lingerie retailers Remember, there are receptionists' areas that customers see but also cubicles, hallways, bathrooms and, most importantly, the break room http://discounteroticlingerie.webs.com - Discounted LingerieLet’s look a bit deeper into the colors In contrast of black, there is white which portrays a pure, clean and innocent image http://cheapsexylingerie.webs.com - Cheap Discount LingerieWomen love the feel of leather on their bare skin, and peeling off a tight leather teddy is a real treat!Lingerie for your baby and you can't lose! Give her a gift of lingerie, and you do yourself a favor! The gift that keeps on giving - all year round! Baby doll lingerie looks sexy and attractive and therefore has become a popular choice among customers Then be sure to role play

    Reply
  • sexy maid costume?

    Posted by Fishnetrh1013 on 03/29/2013 07:45am

    http://cheapsexylingerie.webs.com - sexy lingerieHe was so pleased with the system that he had it installed in all his restaurants It offers fast shipping within the US for orders above $70 http://wholesalesexylingerie.webs.com - Wholesale Sexy LingerieYou must follow these recommendations if you wish your lingerie to last  Along with the lingerie why not put another small gift into the package such as some jewellery or perfume http://G-string.webs.com - Lingerie TeddiesNecklines range from a more traditional scoop neck to a deeply plunging, cleavage-enhancing V-neckHowever, contrasting most other child mermaid costumes that are generally based on the blue-green colors of the sea, the Barbie costume comes in Barbie's favorite color, pink http://Lingeriesv.webs.com - red Lingerie5 Yet the demands of the season mean people need more http://discountsexylingerie.webs.com - china lingerieOut of these bed jackets came the first baby doll lingerie pieces Pick the underwear that fits you, comfortable, and fits the occasion

    Reply
  • French Maid Lingerie

    Posted by Fishnetxa1026 on 03/29/2013 07:21am

    http://Lingeriesv.webs.com - black LingerieThere can also be sets where different items are there, but they are all made of similar material The baby doll lingerie style gets its name from; well http://wholesalesexylingerie.webs.com - Wholesale LingerieFor instance, silk is known to caress the body and evoke a great feel In home parties are very popular http://sexylingeriecostumese.webs.com - Lingerie CostumesGreen also signifies growth and hope Thus lingeries should be shopped the way shoes are bought http://sexycostumesboutique.webs.com - Naughty School Girl UniformSomething else to remember is if the store offers to wrap the lingerie let them The website also includes items on clearance lingerie sale http://G-string.webs.com - Babydoll lingerieThe amount of skin being covered as well as the body parts being accented and held to feature are the biggest determination of the lingerie If you are looking to buy any of these wholesale dresses, you will be satisfied with the variety of colors and fabrics used to manufacture them

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds