Blog > MVC > How to Read the Users Screen Resolution MVC VB.    

Loading

I write this in response to hundreds of rabbit holes I have had to endure to try and Read the Users Screen Resolution.

While I am building an MVC web app I am not using razor, nor am I using ajax queries.

I had discovered a need to know the users screen resolution so I wouldn’t overflow the users screen with a table of 10 or so columns but instead redirect to a mobile version of the page that would fit more efficiently.

After wasting a lot of time on this I discovered a cookie-based approach which I have found to be the best, most reliable way.

Create a Base Controller

My controllers all inherit from a custom base controller that I had built to read the current path name and set it into a ViewBag object. For this to work your controllers should in this case look similar to this:

Namespace Controllers
    Public Class LeadsController
        Inherits BaseController

Then you need to create a new class, in this case called BaseController, and it must then Inherit from Controller in order for your controller to function as it should.

This is where we can place a small but significant piece of code asking the cookies collection if a cookie by the name of “_browserWindowSize” exists and if it does then we want to read its value and set a session variable, which I’ve called “ScreenWidth”, to its value.

As follows:

Public Class BaseController
    Inherits Controller

    Protected Overrides Sub OnActionExecuting(ByVal context As ActionExecutingContext)

        MyBase.OnActionExecuting(context)

        Dim url As String = context.HttpContext.Request.Path
        ViewBag.context = Replace(url, "/", "")

        If context.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize") Then

           Dim browserWindowSize = context.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(",")
           Session.Add("ScreenWidth", browserWindowSize(0))

        End If

    End Sub

End Class

Creating the Cookie

Now all we need to do is create the cookie and where best to do that but in the main “_Layout” view which encompasses every called view.

The JavaScript code below also includes the window height which can be accessed in the BaseController like this:

Session.Add("ScreenHeight", browserWindowSize(1))

You can link to a JavaScript file with this code in it or simply inline it here in the Layout which is what I have done in this example.

Place this code into your Shared _Layout view.

<script>
       var browserWindowSize = getCookie("_browserWindowSize");
       var newSize = $(window).width() + "," + $(window).height();
       var reloadForCookieRefresh = false;

       if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) 
       {
            setCookie("_browserWindowSize", newSize, 30);
            reloadForCookieRefresh = true;
       }

       if (reloadForCookieRefresh)
            window.location.reload();

       function setCookie(name, value, days) {
           var expires = "";
           if (days) {
               var date = new Date();
               date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
               expires = "; expires=" + date.toUTCString();
           }
           document.cookie = name + "=" + (value || "") + expires + "; path=/";
       }

       function getCookie(name) {
       	   var nameEQ = name + "=";
           var ca = document.cookie.split(';');
           for (var i = 0; i < ca.length; i++) {
               var c = ca[i];
               while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                }
            return null;
        }
</script>

Read your Screen Resolution Variables from Anywhere

That’s pretty much the gist of it. Now you can access this screen width or height data from your session anywhere.

I have used it to set a Browser variable that sets the switch between mobile and desktop views in the _Layout View just above the @RenderBody() function as follows:

@If (Request.Browser.IsMobileDevice) Or CInt(Session("ScreenWidth")) < 1000 Then     
    Request.RequestContext.HttpContext.SetOverriddenBrowser(BrowserOverride.Mobile)
Else              
    Request.RequestContext.HttpContext.SetOverriddenBrowser(BrowserOverride.Desktop)
End If

@RenderBody()

Here is the link to the original article and code that I have since modified above for VB: https://stackoverflow.com/questions/11628859/how-can-i-determine-browser-window-size-on-server-side-c-sharp

For more tech tips check out our blog here: https://processit.co.nz/blog

I hope this helps someone out there Read the Users Screen Resolution.


Comments

How to Read the Users Screen Resolution MVC VB. — No Comments

Leave a Reply

HTML tags allowed in your comment: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>