访问由JavaScript编辑的隐藏输入值

时间:2009-07-21 15:49:26

标签: c# .net asp.net javascript dynamic-controls

我在C#代码隐藏文件中动态创建了隐藏的输入控件,然后用JavaScript填充了它们的值。我现在想要在C#中访问这些变量。

Firebug显示值随着JavaScript而改变,但我在后面的代码中得到了原始值。任何见解都会非常感激。

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 个答案:

答案 0 :(得分:2)

这是从请求中获取值的一种方法......

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

答案 1 :(得分:0)

在CreateChildControls中,您明确设置隐藏字段的值。 CreateChildControls每次在页面生命周期中运行(可能多次),当您单击提交时,页面会回发并在运行单击处理程序Update_PlanRisks之前再次运行整个生命周期 - 包括CreateChildControls。

避免此问题的最简单方法是在设置隐藏字段的值之前检查您是否在PostBack中:

if(!IsPostBack)
{
    hiddenField.Value = Convert.ToString(pr.Severity);
}