加载时预选的 Web 窗体模型绑定 CheckBoxList

Web Forms Model Binding CheckBoxList preselected on load

我有一个要填充的复选框列表,也许我可以使用 page_load 并从那里开始工作,对吗?

protected void Page_Load(object sender, EventArgs e)
{ 
   //...
   var query = logic.GetPlanCoverages(planName);
   cbl_MemberCoverages.DataSource = coverages;
   cbl_MemberCoverages.DataBind();
}

但是因为Asp.Net引入了Model Binding,现在我可以拥有这个:

 <asp:CheckBoxList runat="server" ID="cbl_MemberCoverages" 
 SelectMethod="BindMemberCoverages" DataTextField="CoverageName" DataValueField="CoverageCode">
 </asp:CheckBoxList>

在代码隐藏中:

public IEnumerable<PlanCoveragesDomainModel> BindMemberCoverages()
{            
   var planName = logic.GetShortPlanName();
   var query = logic.GetPlanCoverages(planName);
   return query;   
}

但是...模型绑定中有一些我仍然不喜欢的东西,或者当您必须预填充表单时,也许只有我无法弄清楚如何正确使用它。

一个典型的场景是当我想从一个用户列表中编辑一个。我打开一个新页面,我有这个表格,其中包含许多要填充的字段。也许其中一位用户已经分配了其中一些覆盖范围。但目前,我找到的唯一解决方法是:

public IEnumerable<PlanCoveragesDomainModel> BindMemberCoverages([QueryString]string mode)
    {
        if (!"edit".Equals(mode, StringComparison.InvariantCultureIgnoreCase))
        {
            var planName = logic.GetShortPlanName();
            var query = logic.GetPlanCoverages(planName);
            return query;
        }

        var coverages = logic.GetPlanCoverages(CurrentModel.PlanName).Select(c => new ListItem(c.CoverageName, c.CoverageCode)).ToArray();
        cbl_MemberCoverages.Items.AddRange(coverages);
        cbl_MemberCoverages.DataSource = coverages;
        cbl_MemberCoverages.DataBind();

        foreach (ListItem listItem in cbl_MemberCoverages.Items)
        {
            listItem.Selected = CurrentModel.Coverages.Any(c => c.Value == listItem.Value);
        }
        return null;
    }

伙计们,有什么想法吗?

为您的 CheckBoxList 控件实施 OnDataBound 事件。

<asp:CheckBoxList runat="server" ID="cbl_MemberCoverages" 
    SelectMethod="BindMemberCoverages" DataTextField="CoverageName" 
    DataValueField="CoverageCode"
    OnDataBound="cblMemberCoverages_DataBound">
</asp:CheckBoxList>

代码

protected void cblMemberCoverages_DataBound(object sender, EventArgs e)
{
    var chkBoxList = sender as CheckBoxList;
    var item = chkbox.Items.FindByValue(queryStringCoverageCode);
    if(item != null)
        item.Selected = true;
}