13 Dec 2009 @ 5:00 PM 
Bookmark and Share

Over time while using ASP.NET I’ve collected a pretty good handful of best practices that I try to employ on my projects – most of them are things that will simplify the ASP.NET development experience, solutions to common problems, or tips that will just make your life easier.  Most of the best practices are only applicable to WebForms, but some are applicable to ASP.NET MVC as well.

  • Don’t write .NET code directly in your ASPX markup (unless it is for databinding, i.e. Eval statements). If you also have a code behind, this will put your code for a page in more than one place and makes the code less manageable. Put all .NET code in your code-behind.  Things can get complex and difficult to debug very quickly when you’re looking at code executing in two different places.
  • SessionPageStatePersister can be used in conjunction with ViewState to make ViewState useful without increasing page sizes. Overriding the Page’s PageStatePersister with a new SessionPageStatePersister will store all ViewState data in memory, and will only store an encrypted key on the client side.  This will make your pages smaller and download faster if you have a lot of ViewState data for some reason, however it will increase your memory usage on the server – so tread carefully.  See example below for how to use SessionPageStatePersister.
public override PageStatePersister GetStatePersister() {
return new SessionPageStatePersister(this);
  • Create a BasePage that your pages can inherit from in order to reuse common code between pages.  Simple object oriented design principles – if you have common functions between pages, like security for example – put it in a base class that inherits from System.Web.Page, and have your pages inherit from that base page.
  • Create a MasterPage for your pages for visual inheritance.  Don’t use ASP server-side includes.  Pages with vastly different visual styles should use a different MasterPage.  Don’t use a Master page for code inheritance.
  • Make use of the ASP.NET Cache in order to cache frequently used information from your database.  Build (or reuse) a generic caching layer that will wrap the ASP.NET Cache.  If you’re loading the same list from the database into a drop down every time a page loads, you should be pulling that list from the cache based on how dynamic it needs to be.
  • Wrap ViewState objects with Properties on your Pages to avoid development mistakes in spelling, etc. when referencing items from the ViewState collection.  For example, you should only have ViewState["key"] once in your page per property.  See example below.
private int SampleId
get { return ViewState["SampleId"] == null ? 0 : (int)ViewState["SampleId"]; }

set { ViewState["SampleId"] = value; }

  • Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.  This is the reason people always complain about huge viewstate – they’re storing something like DataSets in ViewState (terrible idea).  If you stick to small objects with a limited number of properties or just integer IDs, your ViewState data will not be unmanageably large and ViewState is totally usable.
  • Wrap the ASP.NET Session with a SessionManager class to avoid development mistakes in spelling, etc. when referencing items from Session.  Just another way to cut down simple development mistakes.
  • Make extensive use of the applicationSettings key/value configuration values in the web.config – wrap the Configuration.ApplicationSettings with a class that can be used to easily retrieve strongly-typed configuration settings without having to remember the keys from the web.config.  If you have settings, behaviors, etc. that need to change between different deployments of your application, those should be control via settings in the web.config.  For example, we’ll often get requests like ‘We want feature X to go live at the end of the month” – so build, test, and deploy the update ahead of time.  But, add a web.config value that controls whether or not the feature appears i.e. FeatureXEnabled=”False”, on the day of go live just flip it to “True”.
  • Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes – this will make your styles more manageable.  Just a general web development best practice.
  • Create UserControls in your application in order to reuse common UI functionality throughout your pages. For example, if a drop down list containing a collection of categories will be used in many places in the site – create a CategoryPicker control that will data bind itself when the page is loaded.  This is my #1 time-saving best practice, yet I’m always surprised how often I see the same drop down list with the same data getting used the same way on 20 different pages – yet the same type-unsafe databinding logic is duplicated 20 times!
  • Use Properties on your UserControls to setup things like default values, different displays between pages, etc. Value type properties can be defined on your UserControls and then be set in your ASP.NET markup by using class level properties on UserControls.  This is a great way to get even more mileage out of reusing your UserControls – watch out for increased complexity of your UserControl logic though.
  • Make use of the ASP.NET validation controls to perform simple validations, or use the CustomValidator to perform complex validations.
  • Create an user-friendly error handling page that can be redirected to when an unhandled exception occurs within your website.  Log any exceptions that come to this page.  The redirection can occur via the Page_Error event in your Base Page, the Application_Error event in your Global.asax, or within the error handling section in the web.config.  Basically, whichever method you pick – make sure you’re not letting any exceptions go unhandled or unlogged!
  • When working with pages that use a highly dynamic data driven display, use the 3rd party (free) DynamicControlsPlaceholder control created by Denis Bauer to simplify the code needed to save the state of dynamically added controls between postbacks.  This little control has saved me countless hours of pain in creating pages with highly dynamic UserControls.  One gotcha – if you use event handling delegates in a UserControl, you have to hook them up on every postback, little messy but not a big deal though usually.  Event handlers are the only “state” that isn’t saved between postbacks if you use this control.
  • Turn ViewState off on controls and UserControls that don’t need it.
Posted By: admin
Last Edit: 14 Dec 2009 @ 06:21 PM

Tags: ,
Categories: Uncategorized


Responses to this post » (41 Total)

  1. ASP.NET WebForms Best Practices…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. [...] ASP.NET WebForms Best Practices – John Sprunger shares a number of best practices for ASP.NET Web Forms Development, some of which are also applicable beyond the WebForms world. [...]

  3. Adam says:

    “Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes – this will make your styles more manageable. Just a general web development best practice.”

    Number 1 way to annoy any designer. I can’t stand it when I create common classes in css only to find they have been overwritten by stupid .net inline properties.

  4. [...] ASP.NET WebForms Best Practices Very good advice, things to keep in mind when working with WebForms. Some apply to ASP.NET MVC as well. [...]

  5. [...] ASP.NET WebForms best practices: Algunos consejos básicos, otros como el SessionPageStatePersister no muy conocidos, una lectura recomendada para todo programador de ASP.NET. [...]

  6. [...] ASP.NET WebForms Best Practices – System.Nerd.John.Blog + velmi zajímavý design webu [...]

  7. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  8. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  9. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  10. Aking Web Tech a leading IT company & Provides web services :- website Development in just 1,999 Rs/-, software development like {Billing software, School Management Software, Inventory Software, ERP, CRM}, Domain & Hosting , SEO
    software companies in indore

  11. I got this web page from my pal who shared with me on the topic of this
    site and now this time I am browsing this site and reading very informative articles or reviews at
    this place.

  12. Barbra says:

    I delight in, lead to I found just what I used to
    be taking a look for. You have ended my four day
    long hunt! God Bless you man. Have a nice day. Bye

  13. Enjoy the thrill of games you need to travel to a great range of 25 letters a
    5 mega pixel camera, radio, newspapers, and an covet fashion cheats
    ink pad that doesn t surprise me. Free apps and mobile hand helds that are offered at no
    cost thus making you die however your speed limit. The same as
    instream videos. What you require is to locate my personality walking covet fashion cheats instantly
    towards NPC’s and finishing missions alone at the same demographics as though we never stop.

  14. Undeniably believe that which you said. Your favorite justification appeared to
    be on the net the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about
    worries that they just do not know about. You managed
    to hit the nail upon the top and also defined out the whole thing without having
    side effect , people could take a signal. Will likely be back to
    get more. Thanks

  15. Bo Staff, Sword, Nunchakus, Sai, Tonfas, Kamas, and Escrima Stick are just some
    of the many weapons a student of the martial arts might use.
    If the cooked time is too long, the food will become hard and lose its
    flavor, color and taste. The weapons themselves can come
    in many sizes and forms: metal, wood, plastic, rubber, and foam.

    My weblog taekwondo kamas

  16. If you are planning an expansion to your property its simple that you need to acquire and then install additional
    security sensors in order to protect an extended section of your own house.
    Wireless alarm systems keep off the thieves and burglaries, making your home more secure when you are out.
    In addition, you get a Walkie Talkie that can be used for
    effective supervision of the house or business property.

  17. No matter if some one searches for his necessary thing, so he/she needs
    to be available that in detail, so that thing is maintained over here.

  18. Howdy! This is my first visit to your blog! We are a group
    of volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us useful information to work on. You have done a
    wonderful job!

    Stop by my site: lose weight safely (http://www.dietformula.Info)

  19. Admiring the commitment you put into your blog and detailed information you provide.
    It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed information. Wonderful read!

    I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  20. Aw, this was an extremely good post. Taking a few minutes and
    actual effort to produce a very good article…
    but what can I say… I put things off a lot and don’t manage to get nearly anything done.

  21. Link exchange is nothing else but it is simply placing the other person’s website link on your page at proper place and other person will also do similar in support of you.

  22. Cool blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog stand
    out. Please let me know where you got your theme.
    Many thanks

    My web page corporate Meetings,

  23. If you want to get a good deal from this paragraph then you
    have to apply such strategies to your won blog.

  24. In Iron Force you can buy anything at all with
    the assets this hack helps make. Please verify if
    you have put in Iron Force recreation.

  25. An outstanding share! I’ve just forwarded
    this onto a co-worker who was conducting a littlee research on this.
    And he actually ordered me lunch because I stumbled upon it for him…
    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss this issue here on your web page.

  26. Really when someone doesn’t understand afterward its
    up to other visitors that they will assist, so here it

  27. You are so interesting! I do not believe I’ve read through
    something like that before. So good to discover somebody with a few genuine
    thoughts on this topic. Really.. thanks for starting this up.
    This website is something that is needed on the web, someone with some originality!

  28. Cara says:

    You can certainly see your enthusiasm within the article you write.
    The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe.
    At all times follow your heart.

  29. If you wish for to increase your experience only keep visiting this web page and be updated with the most recent news
    update posted here.

  30. Rachele says:

    I have no intention of knowing my weight, nor do I really care.

    More information on: hypnosis self hypnosis
    hypnotherapy hypnosis myths meditation NLP.
    Note that doing the daily cleaning routine cleaning work to prevent the production of dirt and
    found that dirt should be removed in time, do not let it form a old scale and thick

  31. cow says:

    Thank you for every other excellent post. The place else may anyone get that
    kind of information in such a perfect means of writing?
    I have a presentation next week, and I am at the search for such information.

  32. Fener says:

    I think a large part of this psyop is to get us chasing our tales.I think you are manikg a basic mistake here-”I understand some lenses, like a telephoto lens, will distort the depth of field*, but here it’s extreme. Would a telephoto lens have the foreground car, the middle ground people and cars, and the back ground garage all in perfect focus? Is there technology that does this?”You are confusing depth of field with foreshortening. They are indirectly related but are really different things.Depth of Field is range of distances that are in focus. For a given focal length dof is controlled by the f-stop or iris setting. With the lens iris wide open (small f number) you get a relatively shallow dof and this is often used by photographers to differentiate the subject from the background. Conversely with the lens ‘stopped-down’ (high f-number) or closed iris you get a very deep dof and so both foreground and background can be in focus. An extreme example of this is a pin-hole ‘lens’. Foreshortening if the effect you get with a telephoto or ‘long’ (long focal length) lens that reduces the appearance of perspective, or sense of depth. Press often use extremely long lenses when shooting from a distance to ‘get close’ to the action. Conversely Google StreetView cameras use a ‘short’ or wide-angle lens to get a wide view at a short distance and that makes the background look more distant. This is photography-101.The video ‘Sandy Hook fire station footage filmed elsewhere?’ is a classic example. Is this guy for real? If so he’s pontificating from a basis of ignorance. Or is he deliberately trying to mislead the ignorant and gullible?Re. the pic with sighting lines – the idea is sound but I don’t see where he gets the ‘transits’ used to make the lines.I’m all for people viewing photographs with a critical eye, but is it too much to ask for them to have a basic education in photography before screeching to the world. These people are manikg the Truth Movement look like idiots.

  33. Hi to all, since I am genuinely keen of reading this webpage’s post to be updated on a regular basis.
    It includes pleasant information.

  34. rj palano says:

    Thanks for finally talking about > System.Nerd.John.Blog
    Blog Archive

    ASP.NET WebForms Best Practices < Liked it!

  35. Nero linguistic programming or NLP is known to probably the most pure, organic means because it mainly concerns about the habits
    of a person instead of having to take any supplements.
    Before start with your weight loss plan and burning up extra fat out of your body in general,
    you need to understand why you have fat around your
    belly inside the first place. Drink Water– The only liquid you ought to drink is water.

  36. Definitely imagine that that you stated. Your favorite reason seemed to be
    at the internet the simplest thing to remember of.

    I say to you, I certainly get annoyed while other people consider
    issues that they just don’t realize about. You controlled to hit the
    nail upon the top and also defined out the whole thing with
    no need side-effects , other folks could take a signal.
    Will probably be back to get more. Thank you

  37. Helmut Newton ( Berlín, 31 de octubre mil novecientos veinte –
    Los Ángeles, veintitres de enero 2004 ), nacido
    Helmut Neustädter, era un fotógrafo de tendencia alemán, nacionalizado australiano, conocido
    por sus estudios de desnudos femeninos y la dramatización de la sensualidad.

  38. Hi, always i used to check web site posts here early in the
    dawn, since i like to gain knowledge of more and

  39. [...] pertaining to where and ways to use fotografos famosos de moda mexicanos, you can contact us fotografos famosos De moda mexicanos at our own webpage. Réhahn, fotógrafo francés, está entre los diez fotógrafos de viaje más [...]

  40. Darci says:

    En un momento en el que la estética de la masculinidad y la propia moda para hombre estaba
    cambiando estas fotografías supusieron una absoluta revolución.

  41. En cualquier caso, de lo que sí estoy seguro, es de que Lutton es un bellaco, un mago de feria algo peor.

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Change Theme...
  • Users » 3
  • Posts/Pages » 16
  • Comments » 163
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight


    No Child Pages.