Click here to Skip to main content
Click here to Skip to main content

Automatic style changes of ASP.NET controls as per client's screen resolution

By , 13 Apr 2006
 

Sample Image

View online demo.

Introduction

This article will tell you about a technique through which you can make intelligent ASP.NET websites which will automatically detect the resolution of the visitor's desktop and generate a resolution optimized mark-up of a page, not forcing the visitor to keep the resolution of his/her desktop according to the website's best view resolution.

Basic Idea

It is unpredictable for a website to be dynamic in visual appearance for multiple resolutions. Typically, graphic designers design the page graphics and the elements optimized for a certain screen resolution. Visitors having varying resolutions different from that recommended for the website will experience a less comfortable view of the pages.

Through a mix of ASP.NET and JavaScript, we can build such pages for a website which will show up according to the resolution of the visitor's PC. Let's look further on how to achieve this.

The Approach

These are three basic things that we are using to achieve this task. I am assuming that you are a bit familiar with the following:

  • A little JavaScript
  • ASP.NET simple data binding
  • CSS for dynamic behaviour of pages on different resolutions

Client resolution detection

First, on the initial request, with the help of JavaScript code embedded in our page's .aspx file, we are getting the desktop resolution of the visitor who requested the page.

if ((screen.width == 1280) && (screen.height == 1024))
{...

Storing client and server resolution values

As soon as the client PC resolution is detected in JavaScript, it is being stored in a HTML hidden input control named ClientResolution, which is later accessed at the server side script for comparisons. We use the Request object for accessing the ClientResolution value at the server side. Resolution set on the server is kept in a hidden server control named ServerResolution, which is then used on the client side JavaScript code for comparison.

if ((screen.width == 1280) && (screen.width == 1024))
{ 
    document.getElementById("ClientResolution").setAttribute("value", "1280Res");
...

After we capture the resolutions of the client PC in our conditional checks in JavaScript, we post the page to the server for re-adjustments of the control properties to fit in the visitor's resolution.

var thisform = document.Form1 ;
        
if (clientRes != "")
// if the client resolution is captured,
// then postback to server for changing.
{
    thisform.submit();
} ...

The CSS file for setting up different resolution settings for controls

In our example, I am using CSS classes which contain the attribute definitions of the controls. There is a separate set of attribute definitions in our CSS file for each resolution.

/* following three css classes will be used for 1024x768 resolution*/

.label1024
{
font-size: 11pt;
color: red;
font-family: Arial;
}

.textBox1024
{
width: 120;
height: 40; 
}

.button1024
{
width: 120;
height: 40;
}

.image1024
{
background-image: url(1024.jpg);
width: 1003;
height: 97; 
} ...

Binding control properties with values according to the client resolution

Now that the page has been posted to the server, we now need to adjust our page elements according to the visitor's captured resolution settings. As you can guess, a page can be composed of web server controls as well as HTML controls. We can pretty easily access the properties of web server controls on the server side script (e.g., txtInput.Text), but we cannot access the HTML control properties on the server side. HTML controls are static page elements and are not accessible using server side code.

Now, in order to dynamically set the values of the attributes of the HTML page elements, we are using ASP.NET simple data binding to bind singular values to the attributes. The property (the one that gets and sets the value for the variable) from the server side script returns the value for the control's attribute. This gives the dynamic looks for the static HTML elements of the page.

<!-- server control tag attribute 'CssClass' bound with property TB -->
<asp:textbox id=TextBox1 runat="server" 
     CssClass="<%# TB %>" Width="262px"> </asp:textbox>
<!-- html control tag attribute 'class' bound with property BT -->
<input class="<%# BT %>" id=Button1 type=button 
          value=button Text="me too !"> ...

Now, according to the captured resolution settings sent by the JavaScript code, the property on the server side code returns the CSS class for the page element to be bound with. I have made properties for each page element, which return the CSS class which specifies the control's look and feel.

Below, is an example of the property BT (for button control) returning the different CSS classes on conditional checks:

public string BT
{
    get
    {

        //if page is first time requested, then set 
        //the default resolution setting as 1280x1024
        if (! Page.IsPostBack )
        {
            //Set the Html Hidden Input Control Value 
            //For Reffering on Client Through JavaScript
            ServerResolution.Value="1280Res";
            //Returning CSS class name according to client's resolution 
            return "button1280";

        }

        else if( Request.Form["ClientResolution"] == "1280Res")
        {
            //Set the Html Hidden Input Control Value 
            //For Reffering on Client Through JavaScript
            ServerResolution.Value="1280Res";
            //Returning CSS class name according to client's resolution 
            return "button1280";
        }

        else if( Request.Form["ClientResolution"] == "1024Res")
        {
            //Set the Html Hidden Input Control Value 
            //For Reffering on Client Through JavaScript
            ServerResolution.Value="1024Res";
            //Returning CSS class name according to client's resolution
            return "button1024";
        }

        else if( Request.Form["ClientResolution"] == "800Res")
        {
            //Set the Html Hidden Input Control Value 
            //For Reffering on Client Through JavaScript
            ServerResolution.Value="800Res";
            //Returning CSS class name according to client's resolution
            return "button800";
        }
        
        else
        {
            //if client resolution is not detected yet, 
            //then set default 1280x1024 resolution
            return "button1280";
        }
    }
}

Other Comments

Now, by detecting the visitor's resolution through JavaScript on page access, and then submitting the page on the server and changing the attributes of the controls through simple data binding, we achieve the technique to make intelligent ASP.NET pages that automatically change their appearance according to the desktop resolution of the visitor's PC.

This is just a very basic example where I have demonstrated changing the size, colors, width, height, source etc. of the page elements at different resolutions, both for server controls and HTML controls. You can take your imagination towards countless possibilities after getting the basic idea.

In the sample code, I am just demonstrating the different looks of a page on three different resolutions (1280x1024, 1024x800, 800x600). Of course, you can add settings for as many resolutions as you want.

You may be having a thought that each page would check for the client resolution on each page request, which would be less efficient. Well, what we can do here is, we can put this check on the initial page request, and set up the resolution value in a session variable, and avoid checking for it at each page request.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Faheem Iqbal
Web Developer
Pakistan Pakistan
Member
Faheem is a .net web developer and freelancer working for a canadian development centre named Acumen Prescience. He enjoys playing video games, listening to linkin park, and having good sincere buddies. He has also worked on AJAX and hopes that Microsoft gets some common sense one day and provide developers with AJAX technology in its development platforms !

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThanks Faheem! Pinmemberttatum26 Apr '12 - 8:09 
Way cool! Smile | :)
QuestionHow can I read variables from Javascript to my asp.net C# page ? PinmemberRanSitbon13 Apr '10 - 2:57 
I have a javascript that contains a definition for a specific string.
I want to read this string in my Asp.Net C# code.
 
How can I do that ?
Thanks,
Ran
Questionchanging aps.net page resolution PinmemberRanSitbon13 Apr '10 - 1:23 
Hello,
I'm trying to implement Faheem's sample www.codeproject.com/KB/aspnet/DynamicScreens.aspx
 
1. Where should I place the
public string BT
{
...
}
code section ?
 
2. On Request.Form["ClientResolution"]
I get the error "Identifie expected"
 
Please help
Thanks,
Ran
GeneralRE resizing controls based on screen resolution Pinmemberxerxesthethird25 Mar '10 - 1:54 
Good luck mate. Nice article but unless you are talking about a web site with a single web page and a few controls you will need an army of developers to do this for a professional web site with many pages. This should be something that browsers do automatically with just a parameter setting. And they say this is the 21st century!!!!
GeneralHi Faheem PinmemberOscar Ribbeck8 Jan '08 - 11:58 
I am trying to make your code work ussing .Net programming language, but i still can't do it.
I think i have all but seems that the codebehind is being executed before the javascript code can actually set the values for the hidden field, and make the comparison with the server control, so when the time of binding comes, it doesnt find a value in the hidden field, and literally the class binded on my control is none(i set a default value to avoid return a null value tho, but still is a class name that doesnt belong to my css and i cant get anything with it).
 
So the sequence i could identify would be this one.
 
1)viewstate to hold the settings of currentpage(obviously when the page is rendered for the first time, there are no previous settings to save or to apply over the webform).
2)codebehind to run the load method and the databinding process.
3)the javascript script, which is correctly located on my load() event of the form but still is not working.
 
Could you suggest me a possibly workaround for my problem?.
 
Thank you very much for your help and for your will to teach and help us.
 
Best Regards.
Oscar.
GeneralBanner width Pinmembervas_starf130 Dec '06 - 20:00 
I run a forum by name www.starf1.com
 
Only recently I came to know that my page's banner is distorted when viewed in higher resolution. I have made a fix by changing the "align" tag to "left". But still lot of blank space left which gives the page an ugly look.
 
The code which affects the banner is given below
 
//Specify the slider's width (in pixels)
var sliderwidth="500px"
 
All other dimensions are in "%" but this particular script works only in pixels.
 
I use 800x600 as default and require the cde for the following option:
 

1280x1024
 
1024x800
 
800x600
 
I am not familiar with asp.net and Javascript. Hence, I need help. Can anybody help me please with code! Thanks in advance!
GeneralMultiple Monitors PinmemberAndrew Eisenberg21 Apr '06 - 13:07 
I have two monitors at work. The primary monitor is set at 1280x1024 and my secondary monitor is set to 1024x768. However, whichever screen I open the window on, it says I'm at 1280x1024.
 
Andrew C. Eisenberg
Nashville, TN, USA
GeneralRe: Multiple Monitors PinmemberFaheem Iqbal22 Apr '06 - 1:27 
GeneralJavascript Disabled Pinmemberjscrimsher19 Apr '06 - 11:31 
Do you have any suggestions if the user has javascript disabled? thisform.submit() doesn't work in this instance and disabling javascript is becoming more and more prevalent. Would you add a Submit button and ask them to click it to optimize their web page? Any other suggestions?
GeneralRe: Javascript Disabled PinmemberFaheem Iqbal19 Apr '06 - 21:35 
GeneralJust a thought Pinmemberjobobner13 Apr '06 - 6:12 
I'd leave all the classes the same cssClass="Label" or cssClass="MyTextBox" etc. Develop a style sheet for each resolution. The classes would be called the same in each sheet. Then load just the correct sheet each time.
 
Right now you have properties for each one of your classes and entire blocks of code devoted to determining which style to assign. The property does not cache its value at all so you are rerunning that block for every item tied to each style in the page. By leaving the styles to what they are supposed to be, and abstracting from each object the responsibility of determing its own style you will greatly reduce the amount of code you have to write and the amount of code that is executed on each server trip.
 

GeneralRe: Just a thought Pinmembereggsovereasy13 Apr '06 - 10:16 
GeneralRe: Just a thought Pinmemberbowmanspring17 Apr '06 - 23:30 
GeneralRe: Just a thought Pinmembereggsovereasy18 Apr '06 - 2:22 
GeneralRe: Just a thought Pinmemberjobobner18 Apr '06 - 3:00 
GeneralRe: Just a thought Pinmemberchesterpdt18630 May '06 - 19:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 13 Apr 2006
Article Copyright 2006 by Faheem Iqbal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid