2

I have dynamically created hidden input controls in a C# code-behind file, and then populated 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 original 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;
    }
}

2 Answers 2

2

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

string point1 = Request.Form["point1"];
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

1 Comment

when i add the (!IsPostBack){} my string val = "". how would i get this to access the injected javascript value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.