简体   繁体   中英

Checkbox is not checked on postback ASP NET

I have a asp.net project where I have, lets call them objects. All objects are created in a repeater:

<section class="topbar">
    <asp:Button runat="server" ID="btnSave" OnClick="btnSave_OnClick" Text="Save" />
</section>

<asp:Repeater runat="server" id="gwList">
    <ItemTemplate>
        <div class="block">
            <input type="checkbox"  runat="server" ID="chkObjectSelected" value='<%# ((Object.Object)Container.DataItem).Id %>'/> 

            <label><%# ((Object.object)Container.DataItem).Title %></label>

        </div>
    </ItemTemplate>
</asp:Repeater>

Here comes the problem, none of the selected objects will be set as selected in the postback. Here's the code i use to determine if the objects are checked:

protected void btnSave_OnClick(object sender, EventArgs e)
{   
    List<string> objectIdSelected = new List<string>(); 

    foreach (RepeaterItem oneObject in gwList.Items)
    {
        HtmlInputCheckBox chkObj = (HtmlInputCheckBox)carAd.FindControl("chkObjectSelected");

        if (chkObj.Checked)
        {
            objectIdSelected.Add(chkObj.Value.ToString());
        }
    }
}

try replacing

<input type="checkbox"  runat="server" ID="chkObjectSelected" value='<%# ((Object.Object)Container.DataItem).Id %>'/> 

with this

 <asp:CheckBox runat="server" ID="chkObjectSelected" Value='<%# ((Object.Object)Container.DataItem).Id %>'/> 

and change your code to this :

protected void btnSave_OnClick(object sender, EventArgs e)
{
    List<string> objectIdSelected = new List<string>();

    foreach (RepeaterItem oneObject in gwList.Items)
    {
        CheckBox chkObj = (CheckBox)oneObject.FindControl("chkObjectSelected");

        if (chkObj.Checked)
        {
            objectIdSelected.Add(chkObj.Attributes["Value"].ToString());
        }
    }
}

Put an " !Page.IsPostback " condition around the logic in your Page_Load event. What's probably happening is that your button causes a postback, and the page_load reloads your default (un-checked) value before the button click event fires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM