在ASP.NET 4.5中将值设置为HiddenField

我在ASP.NET 4.5中为HiddenField设置值时遇到了一些问题。

从我所看到的,我已经尝试了以下没有任何运气:

在ASPX中:

  function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('').value = vv; }  

在代码隐藏中:

 ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('" + HiddenField.ClientID + "');", true); 

这会在ClientID中警告垃圾。

我尝试过的另一个解决方案如下。

在.ASPX中:

   function SetHiddenField() { var vv = "HELLO WORLD"; document.getElementById('HiddenField').value = vv; }  

这里的一个问题是.ValueOf在IntelliSense中不存在,只有.ValueOf

在代码隐藏中:

 ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('" + HiddenField.Value + "');", true); 

没有任何事情发生,可能是JavaScript中的错误,因为没有显示警报。

有人能指出我正确的方向吗?

你的第一个标记是好的:

   

将代码更改为此(检查第二行):

  ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SetHiddenField", "SetHiddenField();", true); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert(document.getElementById('" + HiddenField.ClientID + "').value);", true); 

输出应该是这样的:

在此处输入图像描述

编辑:在您的方案中,您可以运行javascript来获取值并强制回发以使用代码中的值。 我会将我的标记更改为:

  

在代码中,我的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, this.GetType(), "SetHiddenField", "SetHiddenField();", 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... } } } 

在隐藏字段标签中添加clientid static,如下所示 –

  

这样ASP.Net就不会用动态ID替换它,并且总是拥有你提供的id,所以它现在有ID HiddenField 。 然后你的第二次尝试应该工作。

更多信息可以在这里找到 –

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode(v=vs.110).aspx