Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine browser window size on server side C#

Tags:

c#

.net

asp.net

How can I get the exact height and width of the currently open browser screen window?

like image 891
MANISHDAN LANGA Avatar asked Jul 24 '12 10:07

MANISHDAN LANGA


People also ask

How do I know the size of my browser window?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.


2 Answers

You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.

At its simplest

var width = $(window).width(); var height = $(window).height(); 

Complete method using hidden form inputs

Assuming you have: JQuery framework.

First, add these hidden form inputs to store the width and height until postback.

<asp:HiddenField ID="width" runat="server" /> <asp:HiddenField ID="height" runat="server" /> 

Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().

Add the following code to your .aspx file within the head element.

<script type="text/javascript"> $(document).ready(function() {      $("#width").val() = $(window).width();     $("#height").val() = $(window).height();      }); </script> 

Result

This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:

var TheBrowserWidth = width.Value; var TheBrowserHeight = height.Value; 

This method provides the height and width upon postback, but not on the intial page load.

Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.

Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.

Update for jquery 3.1.1

I had to change the JavaScript to:

$("#width").val($(window).width()); $("#height").val($(window).height()); 
like image 166
Rich Avatar answered Oct 09 '22 03:10

Rich


So here is how you will do it.

Write a javascript function which fires whenever the window is resized.

window.onresize = function(event) {     var height=$(window).height();     var width=$(window).width();     $.ajax({      url: "/getwindowsize.ashx",      type: "POST",      data : { Height: height,                Width:width,                selectedValue:selectedValue },      contentType: "application/json; charset=utf-8",      dataType: "json",      success: function (response) {             // do stuff      }  } 

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {  public void ProcessRequest (HttpContext context) {     context.Response.ContentType = "application/json";      string Height = context.Request.QueryString["Height"];       string Width = context.Request.QueryString["Width"];      } 
like image 24
Ashwin Singh Avatar answered Oct 09 '22 02:10

Ashwin Singh