前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
function fz(){
var std = "2";
alert(std);
document.getElementById('HiddenField1').value=std;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
项目中有个小功能,在Js中修改一个服务器标签的值,如 document.getElementById("lblClothIndex").innerHTML = result;(比如由“1”修改成“2”),可是在后台通过this.lblClothIndex.Text获得的还是"1"这个老值。后来发现通过调用隐藏控件的方法可以获得最新值,代码如下:
1. 添加一个隐藏控件 <asp:HiddenField ID="HiddenField1" runat="server" Value="" />
<asp:TextBox ID="TextBox1" runat="server">0</asp:TextBox>
<a href="#" onclick="fz()">赋值</a>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
2. 用JS为服务器标签赋值的时候也给隐藏控件赋值
3. 在后台通过 this.HiddenField1.Value代码获得最新值
</div>
</form>
</body>
</html>
后台代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = HiddenField1.Value;
}
}
(完)