使用javascript填充asp隐藏字段的值

时间:2013-01-10 12:43:25

标签: javascript asp.net hidden-field

我想从服务器端访问用户屏幕分辨率。 为此,我有asp hidden控件:

<asp:HiddenField runat="server" ID="hdnScreenResolution" />

实际在页面上呈现的内容:

<input type="hidden" name="ctl00$MainContent$hdnScreenResolution" id="MainContent_hdnScreenResolution" />

我使用javascript函数在其中插入值:

$(document).ready(function () {
   var width = screen.width;
   var height = screen.height;

   var hiddenScreenResolution = document.getElementById('<%= hdnScreenResolution.ClientID
    %>'); 
   hiddenScreenResolution.value = "asass";
});

它位于页面源代码:

       $(document).ready(function () {
            var width = screen.width;
            var height = screen.height;

            var hiddenScreenResolution = document.getElementById('MainContent_hdnScreenResolution'); 
            hiddenScreenResolution.value = "asass";
        });

在服务器端,我检查Page_Load()上的隐藏值:

protected void Page_Load(object sender, EventArgs e)
{
    var hiddenValue = hdnScreenResolution.Value;
}

但值似乎是空字符串。 使用jquery没有帮助。

直接插入:     document.getElementById('&lt;%= hdnScreenResolution.ClientID             %&gt;')。value =“asdasd”; 没有用。

问题是什么?

P.S。我想我在document.ready上捕捉屏幕分辨率为时已晚。 并在页面卸载后触发javascript。所以在初始请求时没有变化来捕获它。

期待回答。

1 个答案:

答案 0 :(得分:1)

在将html发送到客户端并执行jQuery Page_Load之前调用服务器端document.ready,以便在使用javascript在客户端上分配之前访问值,并且应该为空。

您需要从客户端向服务器发送值,您可以使用jQuery ajax进行回发以获取服务器上的屏幕坐标值。

要查看正在发生的事情,只需添加asp:按钮并在其服务器端事件中访问隐藏字段值。

相关问题