Friday, October 16, 2009

How to get Browser height width on server side using ASP.Net Page Methods

You need to know how the ASP.Net Page methods work for this one. You may get some idea from this post as well.

I am not very good at manipulating CSS and Javascript to find out current browser height/width and set the control height/width accordingly so that the page looks right in all types of browsers. Hence I needed to get the Browser Height/Width on the server side and then use the appropriate CSS file to show page correctly.

1st - create Javascript functions to get the height/width:

function getBrowserWidth() {
if (window.innerWidth) {
return window.innerWidth;
else if (document.documentElement && document.documentElement.clientWidth != 0) {
return document.documentElement.clientWidth;
else if (document.body) {
return document.body.clientWidth;
return 0;
function getBrowserHeight() {
if (window.innerHeight) {
return window.innerHeight;
else if (document.documentElement && document.documentElement.clientHeight != 0) {
return document.documentElement.clientHeight;
else if (document.body) {
return document.body.clientHeight;
return 0;

2nd - create a WebMethod in your code behind. I have put this method in my base page so I can use it from any aspx page.

public static void SetResolution(int width, int height)
if (width <= 1024) width = 1024;
if (height <= 768) height = 768;
SiteSession.Current.BrowserWidth = width; //Session["BrowserWidth"] = width;
SiteSession.Current.BrowserHeight = height; //Session["BrowserHeight"] = height;

3rd - now the goal is to call this page method at the time of login or at the time when page resizes

PageMethods.SetResolution(getBrowserWidth(), getBrowserHeight(), voidFn, voidFn);

you can also create a function call it as:
window.resize = function () { PageMethods.SetResolution(getBrowserWidth(), getBrowserHeight(), voidFn, voidFn); }

Now, whenever the page loads and resizes, the browser height width will be stored into Session. You can use that while rendering next/other pages:

4th - in your master page for all pages create a Header as below:

<head id="Head1" runat="server">

And then add appropriate css file:

protected override void OnPreRender(EventArgs e)
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = string.Format("~/css/{0}", GetResFileName());
myHtmlLink.Attributes.Add("rel", "stylesheet");
myHtmlLink.Attributes.Add("type", "text/css");
// Add the HtmlLink to the Head section of the page.

public string GetResFileName()
string fileName = "1280x1024.css";
if (SiteSession.Current.BrowserHeight < 800)
fileName = "1024x768.css";
return fileName;