Setting a value to a HiddenField in ASP.NET 4.5

前端 未结 2 827
遇见更好的自我
遇见更好的自我 2020-12-18 01:43

I\'m having some issues setting a value to a HiddenField in ASP.NET 4.5.

From what I\'ve seen I\'ve tried the following without any luck:

In ASPX:

         


        
2条回答
  •  执念已碎
    2020-12-18 01:52

    Your first markup is good:

    
    
    

    Change the code to this (check the second line):

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

    And the output should be like this:

    enter image description here

    EDIT : In your scenario, you can run javascript to get a value and force a postback to use the value in your code. I would change my markup to this:

    
    

    And in code my Page_Load is like below:

    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...
            }
        }
    
    }
    

提交回复
热议问题