All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET Hosting - ASPHostPortal :: Dynamically Add Controls to ASP.NET Page

clock January 18, 2012 07:26 by author Jervis

Think of ASP.Net web page as a container control containing a set of controls that will render themselves in response to a page request. Here, I'll show you different approaches to add controls (a control can be HTML or server side or System.Web.UI.Control) to ASP.Net web page programmatically at runtime.

Let's quickly create ASP.Net web site and add a new Webform named 'dynamically-add-controls-to-aspnet-page.aspx', say. Set it as 'Start up page' and hit the run button. The page will render with five invisible controls i.e. form1, title and some LiteralControls etc and shows no content.

To add Controls after the </HTML> (at the page bottom): Paste the following code in code behind:

1 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
2 { 
3     protected void Page_Load(object sender, EventArgs e) 
4     { 
5         Label dynamicControl = new Label(); 
6         dynamicControl.Text = "Server side label control"; 
7         Page.Controls.Add(dynamicControl); 
8     } 
9 } 

To add Controls at some index in Controls collection: In the first approach the controls added would be stacked down in the rendering order and placed at page end. You can verify this by running the page and clicking the browser's 'View Source', check out the <span>dynamically added Server side label control</span> at the end. Now we'll see how to add controls dynamically at some place. Let's Paste the following code in code behind:

01 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
02 { 
03     protected void Page_Load(object sender, EventArgs e) 
04     { 
05         Label dynamicControl = new Label(); 
06         dynamicControl.Text = "dynamically added Server side label control"; 
07         // it will dynamically add control right after <body> but before <form>: Check the browser's View Source code 
08         Page.Controls.AddAt(3, dynamicControl);         
09     } 
10 }

Dynamically adding Controls asp:PlaceHolder control: Drag asp:PlaceHolder control from toolbox onto the webform. For reference see the following markup code:

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamically-add-controls-to-aspnet-page.aspx.cs" Inherits="dynamically_add_controls_to_aspnet_page" %> 
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 
04 <html xmlns=""> 
05 <head id="Head1" runat="server"> 
06     <title>dynamically add controls to page</title> 
07 </head> 
08 <body> 
09     <form id="form1" runat="server"> 
10         <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> 
11     </form> 
12 </body> 
13 </html>  

1 public partial class dynamically_add_controls_to_aspnet_page : System.Web.UI.Page 
2 { 
3     protected void Page_Load(object sender, EventArgs e) 
4     { 
5         Label dynamicControl = new Label(); 
6         dynamicControl.Text = "dynamically added Server side label control"; 
7         PlaceHolder1.Controls.Add(dynamicControl); 
8     } 
9 } 

Note that we've added PlaceHolder1 inside the form1 control and in the code behind we're adding dynamicControl to it. Ultimately the set of control(s), that we might added to this PlaceHolder1, will get placed in place of PlaceHolder1. Verify via browser's View Source code.

Dynamically adding asp:Button Control to HTML DIV: Here we'll see how to add a button control to HTML DIV tag at runtime. For this add a DIV inside form tag named 'divHtmlControl' ,say and assign it runat="server" attribute. Paste in the following code in code behind:

01 protected void Page_Load(object sender, EventArgs e) 
02 { 
03     Button dynamicButtonControl = new Button(); 
04     dynamicButtonControl.Text = "dynamically adding asp:Button control to HTML DIV"; 
05     dynamicButtonControl.Click += new EventHandler(dynamicButtonControl_Click); 
07     divHtmlControl.Controls.Add(dynamicButtonControl); 
08 } 
10 protected void dynamicButtonControl_Click(object sender, EventArgs e) 
11 { 
12     Button button = sender as Button; 
13     button.Text = "Click event fired"; 

ASP.NET Hosting - ASPHostPortal :: How to Improve your ASP.NET Site with Caching

clock January 11, 2012 05:53 by author Jervis


In this article, I would like to share my experience and knowledge about ASP.NET Caching and how it can improve your website performance. As you all might know that performance is key requirement for any application or piece of code that you develop.  For mission critical website, Caching is the way to go to significantly enhance your web response times.  Caching is the process of storing frequently used data on the server to fulfill subsequent requests.You will discover that grabbing data or objects from memory is much faster than recreating the web pages or items contained in them from scratch.

When and Why use Caching

A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.

Good candidate to use caching is if you have infrequent chance of data or static content of web page.

For example, Stock market website displaying 20 minutes delay data can actually use data caching to store the data, so that it can reduce database call every time the user refresh the page.

Another good example would be using Partial page caching to store some of the infrequent or static content. If you have websites that show lots of information or features, you can actually group the static or infrequent change content into user controls and then set the Caching for that particular user controls. You can set the amount of time when the caching expires so that it will load new data from database

Type of Caching

1. Output Caching (Page Caching)

The most easiest and simple caching that you can implement. Good for caching the static page that is accessed frequently. You can copy and paste the code below on your ASP.NET page.

<%@ OutputCache Duration="60" VaryByParam="None" %>

Duration attribute specifies how long in seconds that the page will be held in the memory. When the cache expired, the engine will automatically reload and refreshes the page again. If the page never change, you can actually set the duration to very long period.

Valid Parameters for OutputCaching

- VaryByParam

The VaryByParam attribute is for caching different type of page based on the HTTP Post or HTTP Get Protocol e.g You can cache dynamic content based on different query string provided.

<%@ OutputCache Duration="60" VaryByParam="CategoryID" %>

In this case, engine will cache the dynamic page based on the different query string provided. If your page is generating different content based on the query string, then  you need to put that in the output cache directive or else all your users will see the same content.

If you want to cache a new version of the page based on any differences in the Query String parameters, use VaryByParam = "*" as in the following code.

<%@ OutputCache Duration="60" VaryByParam="*" %>

- VaryByControl

VaryByControl can be used to cache the usercontrol inside your page. For example you can cache a user control that contains ComboBox that render all the country name in the world. And perhaps those country data is retrieved from database, this will make significant performance for page loading time.

- VaryByCustom

To make the Cache object even more flexible, Microsoft built in the ability to cache the page based on a string, which is then controlled from the actual code of the application

It does have one "out of the box" property, Browser. When VaryByCustom is set to Browser the page is cached every time a different browser agent and major version number requests the page.

<%@ OutputCache Duration="60" VaryByCustom="browser" %>

If you like to have your own set of Caching rule ,then you might need to tweak some of the code in global .aspx. For e.g You might need to differentiate caching content for different set of users based on cookies called Language. Then you need to copy and paste the following code in your global.asax file.

Code in VB.NET

Overrides Function GetVaryByCustomString(ByVal context as HttpContext,_ByVal arg as String) As String
If arg.ToLower() = "cookies" Then
Dim cookie as HttpCookie = context.Request.Cookies("Language")
If cookie isNot nothing Then
Return cookie.Value
End if
End If
Return MyBase.GetVaryByCustomString(context,arg)
End Function

Code in C#

public override string GetVaryByCustomString(HttpContext context, string arg)
if (arg.ToLower() == "cookies")
HttpCookie cookie = context.Request.Cookies["Language"];if (cookie != null)
return cookie.Value;
return base.GetVaryByCustomString(context, arg);

After that , set the VaryByCustom attribute to "cookies" in your OutputCache directives.
By doing that you will generate different set of caching based on the Client languages cookies. This is just one of the example of doing VaryByCustom caching, you can actually create your own set of caching rules by differentiating caching based on user logged on, and etc.

- VaryByHeader

Varies cache entries based on variations in a specified header

2. Partial Page (UserControl) Caching.

Similar to output Caching, partial page caching allows you to cache certain blocks of your website.You can for example only cache the center of the page. Partial page is achieved with the caching of the user controls.  You can build your ASP.NET pages consisting of numerous user controls and then apply output caching on the user controls you select.  This will caches only parts of the page that you want and leaving other parts of page outside the reach of caching.
This is very nice feature and if it done correctly, it can lead to pages that perform better.

Note :
Typically UserControls are placed on multiple pages to maximize reuse. However, when these UserControls (ASCX Files) are cached with  the @OutputCache Directive , they are cached on per page basis.That means even if a User Control outputs the identical HTML when placed on pageA.aspx as it does placed on pageB.aspx,its output is cached twice.
You can prevent this to happen by adding Shared = true in the output cache directive.

<%@ OutputCache Duration="300" VaryByParam="*" Shared="true" %>

By putting Shared attributed, the memory savings can be surprisingly large.
If you have an ASCX User control using the OutputCache directive,remember that User Control exists only for the first request.

3. Data Caching

Output Caching and Partial Page caching is useful if you want to cache the output of the page. However if you like to cache DataSet object or any Collections object, you can use Data Caching to implement that.

ASP.NET has one class called Cache Object to start caching specific data items for later use on particular page or group of pages. The cache object enables you to store everything from simple name/value pairs to more complex objects like datasets and entire .aspx pages.


Cache("MyDataSet") = myDataSet;


Cache("MyDataSet") = myDataSet;

To retrieve the data from the cache, you can use the code below.


<strong>Dim ds as New DataSet
ds = CType(Cache("MyDataSet"),DataSet)


<strong>DataSet ds = new DataSet();
ds = (DataSet) Cache["MyDataSet"];


As we've just seen, caching Web pages with ASP.NET is amazingly easy, accomplished with a simple line. With this glimpse of ASP.NET's caching abilities, you can improve your Web application's performance. But remember Caching in is a trade off between CPU and memory. How hard is it to make this page versus whether you can afford to hold 200 versions of it. If it's only 5KB of HTML, a potential megabyte of memory could pay off handsomely versus thousands and thousands of database access. Every page of request served from the cache saves you a trip to the database.

Reasons why you must trust

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.

Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions

Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png


Corporate Address (Location)

170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in