3

如何在 asp.net 代码隐藏中获取 HiddenField 值?提前致谢!

  public partial class ReadCard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            this.ClientScript.RegisterStartupScript(this.GetType(), "MyClick ", "<script>ReadCard();</script> ");
            string b= HiddenField1.Value; //How to get the value "123"??
        }
    }

aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta http-equiv="expires" content="0"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <script src="jquery-1.5.2.min.js" type="text/javascript"></script>
         <script type="text/javascript">
             function ReadCard() {
                 $("#HiddenField1").val("123");
             }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </form>
</body>
</html>
4

3 回答 3

4

客户端 ID 不一定与服务器 ID 相同(除非您使用CliendIDMode=Static. 您可以插入服务器标签来获取客户端 ID。

另请注意,您必须将脚本放在document.ready标签内,或者将脚本放在页面底部——否则脚本将找不到 HiddenField1,因为它还没有加载到 DOM 中。

$(document).ready(function() {
    $("<%= HiddenField1.ClientID %>").val("123");
});
于 2012-11-28T07:41:08.830 回答
2

尝试 :

$("#<%= HiddenField1.ClientID %>").val("123");

在 .cs 文件中:

string b= HiddenField1.Value;
于 2012-11-28T07:44:15.880 回答
2

你的问题是你如何设置它。

$("#<%=HiddenField1.ClientID%>").val("123");

您需要使用呈现的控件 ID。

跟进。这段代码

  protected void Button1_Click(object sender, EventArgs e)
        {
            this.ClientScript.RegisterStartupScript(this.GetType(), "MyClick ", "<script>ReadCard();</script> ");
            string b= HiddenField1.Value; //How to get the value "123"??
        }

实际上是一样的:

  protected void Button1_Click(object sender, EventArgs e)
        {
            HiddenField1.Value = "123";
        }

因为您实际上尝试通过注册 javascript 代码来设置值,但是为什么呢?您可以直接从后面的代码中设置该值。

你真的不会在哪里获得那个价值?

于 2012-11-28T07:41:17.287 回答