views:

2619

answers:

2

I have dynamically created hidden input controls in a c# codebehind file, and then populate their values with javascript. I now want to access these variables in c#.

Firebug shows that the values do change with javascript, but i'm getting the origional values back in the code behind. Any insight would be much appreciated.

Javascript:

    function injectVariables(){
       var hidden = document.getElementById("point1");
       hidden.value = 55;
       var hidden2 = document.getElementById("point2");
       hidden2.value = 55;
       var hidden3 = document.getElementById("point3");
       hidden3.value = 55;
       alert("values changed");
    }

ASPX

<asp:Button OnClick="Update_PlanRisks" OnClientClick="injectVariables()" Text="updatePlanRisks" runat="server" />

C#

  protected override void CreateChildControls()
    {
        base.CreateChildControls();

        int planId = Convert.ToInt32(Request.QueryString.Get("plan"));
        planRisks = wsAccess.GetPlanRiskByPlanId(planId);



        foreach (PlanRisk pr in planRisks)
        {
            HtmlInputHidden hiddenField = new HtmlInputHidden();
            hiddenField.ID= "point" + pr.Id;
            hiddenField.Name = "point" + pr.Id;
            hiddenField.Value = Convert.ToString(pr.Severity);

            this.Controls.Add(hiddenField);
        }

    }

    protected void Update_PlanRisks(object sender, EventArgs e)
    {
        foreach (PlanRisk pr in planRisks)
        {
            int planRiskId = pr.Id;
            string planRiskName = "point" + pr.Id;


            HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl(planRiskName);
            string val = hiddenControl.Value;

        }
    }
A: 

In CreateChildControls you are explicitly setting the value of the hidden field(s). CreateChildControls runs each time during the page lifecycle (potentially multiple times), when you click submit, the page posts back and runs through the entire lifecycle again - including CreateChildControls - before running the click handler Update_PlanRisks.

The simplest way to avoid this problem is to check if you are in PostBack before setting the value of your hidden fields:

if(!IsPostBack)
{
    hiddenField.Value = Convert.ToString(pr.Severity);
}
Rex M
when i add the (!IsPostBack){} my string val = "". how would i get this to access the injected javascript value?
ErnieStings
+1  A: 

This is one way to get the value from the request...

string point1 = Request.Form["point1"];
Josh Stodola