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

Asked

Viewed 876 times

1

The idea is to use javascript to detect the screen resolution, and take the value of the variable of this javascript and pass to the variable of C#. The only thing that’s crossed my mind is creating 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;
    }
  • You plan to get the resolution to control the page layout?

  • Yes, you already do this the time in the application. The most common is to use AJAX in these cases. I don’t even know which is duplicate of this, but it has been answered a few times: http://answall.com/search?q=%5Basp.net-mvc%5D+ajax

  • @rodorgas the idea is that I have a component in the navbar, and when the resolution decreased, the content was hidden

1 answer

1

To pass Javascript values 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 downloaded the page is completed. The server does not have access to JS-independent code running in the browser, unless you inform it directly by making a new request.

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

It is possible to do this with JS, but CSS3 introduced the media query, starting the movement of responsive layouts that automatically adjust 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;
  }
}
  • I got it... thanks a whirl

Browser other questions tagged

You are not signed in. Login or sign up in order to post.