Is it possible to pass the value of a Javascript variable to a C # variable?

1

The idea is as follows, use javascript to detect the screen resolution, and get the value of the variable of this javascript and move to the C # variable. The only thing that got into my head is to create an input to manipulate the variables, but I believe you have another method. In practice the idea would be more or less this:

   <script type="text/javascript">
        var varJavascrpt = $(window).width();
    </script>
    @{
        var varCSharp = varJavascript;
    }
    
asked by anonymous 25.12.2016 / 19:50

1 answer

1

To pass values from JavaScript to ASP.NET, a new request (e.g. using AJAX) is required. It is not possible to check the resolution before making the request because JS in this case is client-side, while asp.net is server-side, which means that the JS code will only run in the browser after the request that transferred the page has finished. The server does not have access to the standalone JS code executed in the browser, unless you tell it directly by making a new request.

But this approach is bad because the decision whether or not to display a component in navbar will be dependent on a second request after the page loads. The ideal thing is to do this with client-side technologies so you do not have to go to the server and then go back, thus saving resources, accelerating page load and not depending on JS enabled in the browser.

You can do this with JS, but CSS3 has introduced media query , initiating the movement of responsive layouts that adjust automatically according to the resolution (and the server is agnostic about it). For example, to hide a navbar when the resolution is less than or equal to 600px, do so:

@media (max-width: 600px) 
{
  .navbar {
    display: none;
  }
}
    
25.12.2016 / 21:33