在加载

时间:2017-10-02 14:32:51

标签: c# asp.net webforms model-binding checkboxlist

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

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

但是因为Asp.Net引入了模型绑定,现在我可以拥有它:

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

伙计们,有什么想法吗?

1 个答案:

答案 0 :(得分:2)

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