我在ASP.NET 4.5中为HiddenField设置值时遇到了一些问题.
从我所看到的,我已经尝试了以下没有任何运气:
在ASPX中:
<asp:HiddenField ID="HiddenField" runat="server" value="" /> <script type="text/javascript"> function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('<%=HiddenField.ClientID%>').value = vv; } </script>
在代码隐藏中:
ScriptManager.RegisterStartupScript(this.Page,this.GetType(),"SetHiddenField","SetHiddenField();",true); ScriptManager.RegisterStartupScript(this.Page,"alert","alert('" + HiddenField.ClientID + "');",true);
这会在ClientID中警告垃圾.
我试过的另一个解决方案如下.
在.ASPX中:
<asp:HiddenField ID="HiddenField" runat="server" value="" /> <script type="text/javascript"> function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('HiddenField').value = vv; } </script>
这里的一个问题是,IntelliSense中不存在.value,仅存在.ValueOf.
在代码隐藏中:
ScriptManager.RegisterStartupScript(this.Page,"alert('" + HiddenField.Value + "');",true);
没有任何事情发生,可能是JavaScript中的错误,因为没有显示警报.
有人能指出我正确的方向吗?
解决方法
你的第一个标记是好的:
<asp:HiddenField ID="HiddenField" runat="server" value="" /> <script type="text/javascript"> function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('<%=HiddenField.ClientID%>').value = vv; } </script>
将代码更改为此(检查第二行):
ScriptManager.RegisterStartupScript(this.Page,true); ScriptManager.RegisterStartupScript(this.Page,"alert(document.getElementById('" + HiddenField.ClientID + "').value);",true);
输出应该是这样的:
编辑:在您的方案中,您可以运行javascript来获取值并强制回发以使用代码中的值.我会将我的标记更改为:
<script type="text/javascript"> function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('<%=HiddenField.ClientID%>').value = vv; __doPostBack('<%=HiddenField.ClientID%>','') } </script>
在代码中,我的Page_Load如下所示:
protected void Page_Load(object sender,EventArgs e) { if (!IsPostBack) { // Register JavaScript which will collect the value and assign to HiddenField and trigger a postback ScriptManager.RegisterStartupScript(this.Page,true); } else { //Also,I would add other checking to make sure that this is posted back by our script string ControlID = string.Empty; if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"])) { ControlID = Request.Form["__EVENTTARGET"]; } if (ControlID == HiddenField.ClientID) { //On postback do our operation string myVal = HiddenField.Value; //etc... } } }