How to get HiddenField value in asp.net code-behin

2020-02-14 10:21发布

How to get HiddenField value in asp.net code-behind? Thanks in advance!

  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>

3条回答
家丑人穷心不美
2楼-- · 2020-02-14 10:49

Try :

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

And in .cs file:

string b= HiddenField1.Value;
查看更多
迷人小祖宗
3楼-- · 2020-02-14 10:50

The client ID isn't necessarily the same as the server ID (unless you're using CliendIDMode=Static. You can insert a server tag to get the client ID.

Note also that you have to put the script inside a document.ready tag, or put the script at the bottom of the page -- otherwise the script won't find HiddenField1, as it will not have been loaded into the DOM yet.

$(document).ready(function() {
    $("<%= HiddenField1.ClientID %>").val("123");
});
查看更多
趁早两清
4楼-- · 2020-02-14 11:00

Your issue is on how you set it.

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

You need to use the rendered control id.

Follow up. This code

  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"??
        }

is actually the same as :

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

Because you actually you try to set the value with registering a javascript code, but why ? you can direct set that value from code behind.

Where do you really wont to get that value ?

查看更多
登录 后发表回答