February 8th, 2014

Get Browser Height and Width on Server Side in ASP.NET

A Responsive Web Design is not only UI changes but also to optimize server side logic for performance. Suppose you are displaying bulk data in desktop environment. But if same data are sent to mobile device, it will make website too slow even the layout is made adaptive on client side. To implement server side logic, we need client side information like browser width and height. In this article, we will implement to get browser height and width on server side in ASP.NET.


Environment: VS2012,.NET Framework 4.5, ASP.NET Web Form, C#

Add Handler:

1. Right click on the project in solution explorer > Add New Item > Generic Handler > Enter name “windowSize.ashx

2. We are going to use Session for storing browser width and height, implement IRequiresSessionState also

using System;
using System.Web;

public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState  {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";
        
        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
        context.Response.Write(output);
        
        context.Session["BrowserWidth"] =  context.Request.QueryString["Width"]; 
        context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
    }

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }
}

It returns isFirst = true/false by checking session value. If it is true we will reload browser window.

Add Ajax Request:

3. Add a new javascript file “BrowserWindowSize.js” and add following code:

window.onresize = function (event) {
    SetWidthHeight();
}
function SetWidthHeight() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: "windowSize.ashx",
        data: {
            'Height': height,
            'Width': width
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {     
        if (data.isFirst) {
            window.location.reload();
        };
    }).fail(function (xhr) {
        alert("Problem to retrieve browser size.");
    });
    
}
$(function () {
    SetWidthHeight();
});

On Page:

4. In Default.aspx, reference to javascript files in head tag

 <script src="Scripts/jquery-1.9.1.min.js"></script>
 <script src="Scripts/BrowserWindowSize.js"></script>

Add a label in body tag

  <asp:Label ID="lblDim" runat="server" Text=""></asp:Label>

Use Session:

We will get browser width and height from Session variables.

  protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["BrowserWidth"] != null)
        {
            // Do all code here to avoid double execution first time
            // ....
            lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
        }
    }

When this page is opened in browser, Page_load fires but Session is null first time. When javascript file is loaded, it calls handler, sets values in session variables and reloads the page first time.

Output:

responsive browser width height

We have implemented to get browser width and height on server side. It is very useful to implement server side logic for responsive web design. Share your opinion in the comment box. Enjoy programming!!