Top 10 Useful Attributes & Properties for ASP.NET Controls

This article tries to highlight a few useful attributes/properties of ASP.NET controls.

1. ClientIDMode

The ID's that get auto-generated for the ASP.NET controls when they render, are known to cause trouble and annoyance when we have to refer them in the client scripts. Although, this auto-generation is a simple concatenation of the naming container and the id, the ids generated are still not predictable to a good extent.

ASP.NET 4.0 addresses this issue with the ClientIDMode property. It lets you control the way these ID's are generated. The ClientIDMode takes one of the four possible values. Viz. AutoID, Static and Predictable and Inherit.

Below is a brief explanation of what the modes mean:

  • AutoID - This behavior causes the generation of Id's as per the versions prior to 4.0.
  • Static - This behavior causes the Id's that you specify to be retained. There would be no change in them when they are rendered.
  • Predictable - This behavior lets you specify a suffix that would be merged with the ID property of the container control.
  • Inherit - This behavior lets you inherit the settings as the parent control.

Note that the default ClientIDMode for the Page is AutoID and for the control is Inherit. You can set the ClientIDMode value through the Page attribute.

You set the page-level value in the @ Page directive. You can also do this for all the pages of your application by modifying your web configuration file.

  <system.web> 
    <pages clientIDMode="Predictable"></pages> 
  </system.web>

2. Meta Keywords and Meta Description

The Page class adds two new properties in ASP.NET 4.0 - MetaKeywords and MetaDescription. These two properties can be set at run time, and can be driven through database or any other source.

You can set these properties at run time, which lets you get the content from a database or other source, and which lets you set the tags dynamically to describe what a particular page is for.

The following Page markup shows you the two attributes in action.

   <%@ Page Language="C#" AutoEventWireup="true"   Keywords="keyword1, keyword2" 
     Description="my description" %>  
 

3. Persisting Row Selection in Data Bound Controls

Data bound ASP.NET controls like Grid View support row selection. But they would select the same numbered row on every page of the control. Persistence in row selection is missed. That is because versions prior to ASP.NET 4.0 selected the row on the subsequent pages based on the row index. The new version of ASP.NET provides us an Intuitive way of solving this issue.

The data bound controls now support an EnablePersistedSection property which helps us achieve this. Following markup shows us the EnablePersistedSelection property used in the List View control.

  <asp:ListView ID="topRanks" runat="server" EnablePersistedSelection="True" DataSourceID="dsRanks" DataKeyNames="rankid">
   	 <ItemTemplate>
  …
   	 </ItemTemplate>
    	<SelectedItemTemplate>
     		 …
    	</SelectedItemTemplate>
  </asp:ListView>

4. AutoEventWireup

One of the less used but better known attribute of ASP.NET is AutoEventWireup. In simplest terms, it allows the calls to the page events automatically without the use of explicit delegates when set to true.

The following markup shows the usage of AutoEventWireup attribute:

  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" …. %>

Its default value is true. The primary disadvantage of the usage of AutoEventWireup attribute can be read from the MSDN page that talks about the Control Event Model: "This limits your flexibility in how you name event handlers. Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant."

5. Header Property of Page

The Page class now provides us the Header property. You can bind this now at runtime. The following sample code shows you how to explicitly set the Title property.

  this.Header.Title = "My page title";

This property comes in handy, when you have to dynamically associate a style sheet based on a rule. Printing a page is an ideal candidate for this situation.

  HtmlLink printLink = new HtmlLink ();
  printLink.Attributes.Add ("type", "text/css");
  printLink.Attributes.Add ("rel", "stylesheet");
  printLink.Attributes.Add ("href", "css/print.css");
  this.Header.Controls.Add (printLink);

6. AssociatedControlID Property

You can associate one control to another server control in a web form. This can be done using the AssociatedControlID property of the server control. This is useful in cases where you want to set the hotkey for an associated control based on some action.

The default value for this property is an empty string, which indicates that the control is not associated with any other server control on the web form. The following markup shows how a Textbox is associated with the Label server control.

  <asp:label ID="lblUserName" AssociatedControlID="txtUserName" runat="server" Text="User name:" />
  
  <asp:TextBox ID="txtUserName" runat="server" />

7. ControlState Property

One of the most important ASP.NET's state management technique is the ViewState. It allows you to preserve values between round trips to the webserver. But since this can be turned off at the parent level, this was not a reliable method to store information.

ASP.NET 2.0 introduced the private ViewState for a server control called the "ControlState". This can be used to store critical information of a control and ASP.NET would take care of the serialization and deserialization of this.

Note that, this has to be used judiciously as it can affect the performance of the page. Look at the references section for an excellent article on how to use this.

8. Control.PreserveProperty

Rick Strahl has an implementation that provides us an alternative against the conventional view state usage. It has a PreservedProperties collection that holds the control id and the property name. Look at the references section for the link to "Implementing an ASP.NET PreserveProperty Control"

9. Browser Based Properties?

ASP.NET version 2.o provides us a way to specify the browser filter for a property. I stumbled on this fact when I hit the Ryan Farley's blog. He too stumbled on this when he hit the John Katsiotis's page.

The fact is that you can set a different value for a property based on the browser. Look at the example below: (from Ryan Farley's blog)

   <asp:Button runat="server" ID="buttonText"  ie:Text="IE Button" 
       ie:OnClientClick="javascript:alert('Hello IE!');" mozilla:Text="FF Button" 
       mozilla:OnClientClick="javascript:alert('Hello Firefox!');" 
       Text="General Button" OnClientClick="javascript:alert('Hello everyone else!');" />
 

Interesting, eh?

10. PreviousPageType Directive

The PreviousPageType directive is part of the ASP.NET 2.o Cross-page postback mechanism that allows you to specify the virtual path of the source page for strongly typed access to the source page.

The posted data would be normally accessed through the PreviousPage property and the FindControl method which involved a cast. However, using the strongly typed PreviousPageType directive lets you access the public properties in the strongly-typed manner without a cast. There are no FindControl methods to be called too.

For e.g, Let's say you have a page called "firstpage.aspx" that has a public property called "FirstProperty". Now, in your second page, say "secondpage.aspx" you would need to add the directive to the page like:

  <%@ PreviousPageType VirtualPath=" firstpage.aspx" %>

And then called the property of the firstpage like this:

  var firstPageProperty = PreviousPage.FirstProperty;

Thanks for reading!

References

Implementing an ASP.NET PreserveProperty Control
GridView.EnablePersistedSelection Property
ASP.NET Web Server Control Event Model
ControlState Property Demystified
RyanFarley's blog



About the Author

Srinath M S

I would love to leave a footprint in this flat world

Comments

  • process of launching our new product Wonder Years Retirement

    Posted by Alisazcrk on 05/24/2013 11:55pm

    policyholder dies during the course of the policy then Bharti http://www.baidu.com crop protection chemicals became integral part of world-wide

    Reply
  • Exploration Berlin world bright and beautiful contest the source of lightning Boerte likes to eat chicken most

    Posted by ioftyabeov on 05/17/2013 06:34pm

    Exploration Berlin world bright and beautiful contest " the source of lightning " Boerte likes to eat chicken most Sport weeklyEngage by special arrangement "All Yo" the direction that Zhang Luping of editor in chief reports to along Boerte double arm indicates, " all Yo " magazine reporter and reporter of engage by special arrangement, pay a visit 3 times abandon heart of Wu Dekang calm (Sherwood Content) , teleilaoni saves Jamaica (the hamlet of a remote mountains of Trelawny) , the source of alleged lightning. Boerte destroys a man on contest of world bright and beautiful record of 100 meters of worlds. Examine atlas The element that makes this secret world is so mediocre: Composition of ghost of the compound with fascicular fireweed, yam, thunder, just repair the highway that connect, drug-store, shabby house to abandon, the men and women with lazy languid, still have the dog that bark makes. But, as a result of Boerte's cause, the person that come here is subliminal almost can think of familiar to the ear of a Chinese can the source of substantival peach blossom of detailed. In alien eye, everything here is flaring cannot the brightness that character says, once attempt to come with scientific spirit,can anatomize it, final however the disappointment of sink profundity. In the oldest age, each person needs occultism of have the aid of, the eccentric soul of ability handholding world; Now, when cannot enter a maze, occultism runs amuck as before, carrying the image of a lot of magnificent and story at the same time. When landed yam, it is the content of daily allay one's hunger of poor and lower-middle peasants nevertheless, come across good year, deposit anxious, countrywoman follows yam innocent and craftily Boerte link up with, aid into what publicize lightning however unexpectedly push an agent. This then ordinary other people, also with most social status of bewildered purpose kind soares, do not book still cannot buy really. Boerte's aunt, er of Li Li rich is special, become us 3 times exclusively to interview the local of the object, a grocery store opened in the village, in its ignore in the smile that concealed shows suddenly, she tries hard the arrival outside making believes, the yam in inn is the nephew's recipe really. Mom Zhan Ni of Boerte nots is more over and [url=http://jordankicks.page4.me/]jordan sneakers for sale[/url] over, be forced to recollect the extraordinary hour that the son is born, her answer also more and more suffer reporters to welcome, the actor's lines that adds newly is: He begins to be moved greatly from 3 weeks kept. Page number: 1 2 3 Issue one page

    Reply
  • you can rapidly spot the items that are most easily obtained.

    Posted by Andreadht on 05/15/2013 06:03am

    television. He has been nominated and received several awards http://www.baidu.com clip instruction, for $14.99. You might even now will need the

    Reply
  • fake oakleys

    Posted by bgliliImpumpffp on 03/29/2013 10:41am

    http://discountoakleysunglassesho.webs.com - discount oakley sunglasses discount ray ban http://sunglasspomoteauthentic.webs.com - cheap sunglasses oakleys for cheap http://guccicheapsunglass.webs.com - cheap ray ban,,,, ray ban wayfarer cheap http://discountsunglassessale.webs.com - discount ray ban discount ray ban http://sunglassdicountsaleu.webs.com - cheap sun glasses cheap ray ban wayfarer

    Reply
  • cheap fake oakleys

    Posted by egliliImpumpceo on 03/29/2013 10:09am

    http://discountsunglasseshoo.webs.com - discount ray ban cheap oakleys http://sunglasssaleulow.webs.com - cheap ray ban discount sunglasses http://onlineguciisunglass.webs.com - cheap ray ban wayfarer replica sunglasses http://guccicheapsunglass.webs.com - ray ban cheap oakley sunglasses cheap http://qualityguccisunglass.webs.com - cheap ray ban sunglasses fake ray ban

    Reply
  • Naughty School Girl Uniform

    Posted by Fishnetpr1036 on 03/29/2013 08:44am

    http://lingeriemall.webs.com - red lace lingerieWhether you are searching for vintage-style or more modern baby doll lingerie, you will find sizing a breezeHoliday stress and holiday blues are such well-known terms now that they should probably be in the dictionary but aren't http://SexyTeddies.webs.com - sexy teddyWhile purchasing babydoll chemises, consider the neckline http://sexycostumesboutique.webs.com - cop costumeYou are no longer Jennifer, the accountant However, the item has also continued to evolve http://SexyChemise.webs.com - womens chemiseMermaids are a legendary mystical creatures of the deep seas, that posse the upper body of a female and lower body of a fish, and are known to be attention-grabbing and beautiful Included in its website are listings of hot offers, bestsellers, latest arrivals and on sale products http://discountsexylingerie.webs.com - china lingerieLingerie are not limited to bras and panties The tops are tight, with thin straps and usually a V neckline, although there are boxer sets with normal t-shirt tops

    Reply
  • cop costume

    Posted by Fishnetjz1030 on 03/29/2013 08:42am

    http://cheapspicylingerie.webs.com - Cheap Discount LingerieYou might spend a lot of time getting the perfect gift but with a wrong color?Wicked Temptations http://wholesalesexylingerie.webs.com - sexy lingerie wholesaleBoxer sets have grown to be extremely popular nowadays It can be quite sensual since it brings the body contours to proportion and this is why the sizing matters http://discounteroticlingerie.webs.com - Erotic LingerieBoxer sets have grown to be extremely popular nowadays It can be quite sensual since it brings the body contours to proportion and this is why the sizing matters http://cheapspicylingerie.webs.com - plus size corsets cheapNecklines 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://sexycostumesa.webs.com - Naughty School Girl UniformLingrie is hygienic underwear and basically meant for females Buying wholesale products are the best way to increase your profit potential

    Reply
  • Cheap Discount Lingerie

    Posted by Fishnetic1019 on 03/29/2013 08:09am

    http://sexylingeriecostumes.webs.com - Intimate ApparelIt helps to know what type of panties she likes to wear too - thongs, briefs, or high cut bikini If you purchase something like the lingerie she already has and in colors you know she likes, it will probably make her happy http://womenssexyclothes.webs.com - Sexy CostumesAfter all, from Oct This can include finding a pair of shoes that seamlessly match your costume's concept http://sexycostumesa.webs.com - Maid Lingeries most popular costume storeBabydoll chemises come in a wide variety of steamy materials, such as silk and nylon http://SexyTeddies.webs.com - sexy lingerie teddiesIncluded in its website are listings of hot offers, bestsellers, latest arrivals and on sale products Sometimes the same style looks absolutely different in other color – never forget that http://sexylingerieshops.webs.com - Trashy LingerieUnless you know, have a look at her nightgown/lingerie drawer before you leave If you're a sexy cowgirl, grab a pair of cowgirl boots; a ballerina, look for ballerina slippers; a Greek goddess, find a pair of gold gladiator heels, etc, etc

    Reply
  • Nurse Costumes

    Posted by Fishnetsb1080 on 03/29/2013 07:46am

    http://sexycostumesboutique.webs.com - Naughty School Girl UniformYou can purchase your baby doll lingerie at online stores or local shops When it comes to sizes, it is vital to take some measurements first of your bust and try to figure out the specific size of your bra http://G-string.webs.com - womens thongs?However, you must also ensure that having spent your hard earned money on your beautiful lingerie is not just enough, you also need to take care that you do not treat your lingerie that way you treat your jeans and pants A thong can be a sexy piece of underwear with the right outfit but it can also be uncomfortable at times http://discountsexylingerie.webs.com - Chinese ManufacturerSo beware of choosing the color for someone with different culture The look of the lingerie is only half of how it can be considered hot; the way the woman feels when she wears it is the other http://lingeriemall.webs.com - lacey lingerieIf you are wearing a bra where you are coming out of it or your curves not smooth than the bra may be too small The lingerie will do the work for you with no question http://lingeriemall.webs.com - white lace lingerieThey have lingerie from bustiers, corsets and babydolls The best thing is that all these dresses are available both online and offline at affordable prices for the customers

    Reply
  • snapbacks wholesale

    Posted by xxds2cb on 03/29/2013 01:32am

    [url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online h udki [url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats x sfyw[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap g evsb[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale l dfjo[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps y aprl[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale h gnui [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale o dxie [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks r rmbk[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats k tjck[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale l cfpx[url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats v gwbo[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale r xgpt [url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale b dsnf [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps k usoc[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap s xcdy[url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats s lvcl[url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale h zqub[url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online b riqb

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds