【问题标题】:unable to get checked property of htmlinoutcheckbox on server side(code behind)无法在服务器端检查 htmlinoutcheckbox 的属性(代码隐藏)
【发布时间】:2013-07-23 07:06:42
【问题描述】:

我已经从后面的代码动态创建了一个 html 输入复选框,在将复选框呈现到 aspx 页面后,我无法在按钮单击事件上获取这些复选框的选中属性。 week 是一周中所有日期的枚举。这里是示例代码。

HtmlInputCheckBox chkbx = new HtmlInputCheckBox();
chkbx.Attributes.Add("id", ((week)i).ToString());
chkbx.Attributes.Add("runat", "server");
chkbx.Attributes.Add("name", ((week)i).ToString());
chkbx.Attributes.Add("value", "checked");

HtmlGenericControl label = new HtmlGenericControl("label");
label.Attributes.Add("for", ((week)i).ToString());
if (i == 1 || i == 7)
{
    label.Attributes.Add("class", "dow disabled");
    label.Attributes.Add("disabled", "true");
}
else
{
    label.Attributes.Add("class", "dow");
    chkbx.Checked = true;                    
}
label.InnerText = ((week)i).ToString().Substring(0,2);
_dowcontrol.Controls.Add(chkbx);
_dowcontrol.Controls.Add(label);

ASPX 页面

<body>
    <form id="form1" runat="server" method = "post">
        <t2:mycontrol ID="SampleControl" runat="server" >
        </t2:mycontrol>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </form>
</body>

ASPX.CS 页面 按钮点击里面应该是什么?

试过了

Request.Form["***"], FindControl("***")

【问题讨论】:

    标签: html asp.net


    【解决方案1】:

    为了让您动态创建的控件与页面生命周期中的视图状态、事件和其他阶段进行交互,需要在Init 事件中创建它们。在生命周期后期创建这些控件将使它们无法参与 post 值绑定、视图状态绑定等。还请注意,您必须在每次回发时重新创建控件。

    protected void Page_Init(object sender, EventArgs e)
    {
        // Do any dynamic control re/creation here.
    }
    

    【讨论】:

    • 上面的 .cs 代码是用 createchildcontrols 写在另一个类中的,它继承了 control 和 Inamingcontainer 类。并且所有标记代码都存在于另一个 aspx 页面中。
    • createchildcontrols 为时已晚。您需要在Init 事件中重新创建控件。查看自定义控件的生命周期:msdn.microsoft.com/en-us/library/aa719775(v=vs.71).aspx
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多