如何确定服务器端 C# 上的浏览器窗口大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11628859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I determine browser window size on server side C#
提问by MANISHDAN LANGA
How can I get the exact height and width of the currently open browser screen window?
如何获得当前打开的浏览器屏幕窗口的确切高度和宽度?
采纳答案by Rich
You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.
您可以使用 Javascript 来获取视口的宽度和高度。然后通过隐藏的表单输入或 ajax 将值传回。
At its simplest
最简单的
var width = $(window).width();
var height = $(window).height();
Complete method using hidden form inputs
使用隐藏表单输入的完整方法
Assuming you have: JQuery framework.
假设您有:JQuery 框架。
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().
接下来我们要获取窗口(视口)的宽度和高度。JQuery 有两种方法,恰如其分地命名为 width() 和 height()。
Add the following code to your .aspx file within the head element.
将以下代码添加到您的 .aspx 文件中的 head 元素中。
<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.
关于 UpdatePanels 的注意事项:如果您通过 UpdatePanels 回发,我相信隐藏的输入需要在 UpdatePanel 内。
Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.
或者,您可以通过 ajax 调用回发这些值。如果您想对窗口大小调整做出反应,这很有用。
Update for jquery 3.1.1
jquery 3.1.1 的更新
I had to change the JavaScript to:
我不得不将 JavaScript 更改为:
$("#width").val($(window).width());
$("#height").val($(window).height());
回答by Ashwin Singh
So here is how you will do it.
所以这是你将如何做到的。
Write a javascript function which fires whenever the window is resized.
编写一个 javascript 函数,该函数在调整窗口大小时触发。
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"];
}
回答by Pierre-Olivier Pignon
There is a solution to solve page_onload problem (can't get size until page load complete) : Create a userControl :
有一个解决 page_onload 问题的解决方案(在页面加载完成之前无法获取大小):创建一个 userControl :
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ClientSizeDetector.ascx.vb" Inherits="Project_UserControls_ClientSizeDetector" %>
<%If (IsFirstTime) Then%>
<script type="text/javascript">
var pageURL = window.location.href.search(/\?/) > 0 ? "&" : "?";
window.location.href = window.location.href + pageURL + "clientHeight=" + window.innerHeight + "&clientWidth=" + window.innerWidth;
</script>
<%End If%>
Code behind :
背后的代码:
Private _isFirstTime As Boolean = False
Private _clientWidth As Integer = 0
Private _clientHeight As Integer = 0
Public Property ClientWidth() As Integer
Get
Return _clientWidth
End Get
Set(value As Integer)
_clientWidth = value
End Set
End Property
Public Property ClientHeight() As Integer
Get
Return _clientHeight
End Get
Set(value As Integer)
_clientHeight = value
End Set
End Property
public Property IsFirstTime() As Boolean
Get
Return _isFirstTime
End Get
Set(value As Boolean)
_isFirstTime = value
End Set
End Property
Protected Overrides Sub OnInit(e As EventArgs)
If (String.IsNullOrEmpty(Request.QueryString("clientHeight")) Or String.IsNullOrEmpty(Request.QueryString("clientWidth"))) Then
Me._isFirstTime = True
Else
Integer.TryParse(Request.QueryString("clientHeight").ToString(), ClientHeight)
Integer.TryParse(Request.QueryString("clientWidth").ToString(), ClientWidth)
Me._isFirstTime = False
End If
End Sub
So after, you can call your control properties
所以之后,你可以调用你的控件属性
回答by John
I went with using the regex from detectmobilebrowser.comto check against the user-agentstring. Even tho it says it was last updated in 2014 it was accurate on the devices I tested.
我使用detectmobilebrowser.com 中的正则表达式来检查user-agent字符串。即使它说它最后一次更新是在 2014 年,但它在我测试的设备上是准确的。
Here is the C#code I got from them at the time of submitting this answer:
这是C#我在提交此答案时从他们那里得到的代码:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%
string u = Request.ServerVariables["HTTP_USER_AGENT"];
Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4)))) {
Response.Redirect("http://detectmobilebrowser.com/mobile");
}
%>
回答by Santiago quits SO
Here's an Ajax, asxhhandler and session variables approach:
这是 Ajax、asxh处理程序和会话变量方法:
Handler:
处理程序:
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(); }
}
}
Javascript:
Javascript:
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 aspx file:
在 aspx 文件中:
...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...
Code behind:
后面的代码:
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"];
}
}
Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net
来源:https: //techbrij.com/browser-height-width-server-responsive-design-asp-net

