【问题标题】:ASP.NET Server control with an additional bindable field带有附加可绑定字段的 ASP.NET 服务器控件
【发布时间】:2011-07-21 13:08:14
【问题描述】:

我创建了一个自定义服务器控件,从 System.Web.Contols.CheckBoxList 派生来自定义 CheckBoxList 的呈现方式。我还想添加另一个可绑定字段并在CheckBoxList.RenderItem() 方法中获取该字段的值。我要创建的字段应包含一个值,该值指定是否选中 CheckBoxListItem。我读过一些关于自定义 DataFields 的文章,但从未详细解释过。

为了更好地解释我似乎无法理解的内容,我在课堂上包含了一部分内容。

public class ListedCheckBoxList : CheckBoxList
{
    protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
    {
        if (itemType != ListItemType.Item)
            return;

        var item = base.Items[repeatIndex];

        string cbxHtml = string.Format("<input type=\"checkbox\" value=\"{0}\" name=\"{1}\" /> {2}",
            item.Value,
            string.Concat(this.ClientID, repeatIndex),
            item.IsChecked, // <-- My custom bindable field
            item.Text);

        writer.Write(cbxHtml);
    }
}

当在 .aspx 页面中使用这个控件时,我试图像这样绑定它

<abc:ListedCheckBoxList ID="cbxList" runat="server"
     DataValueField="UserId"
     DataTextField="UserFullName"
     DataIsCheckedField="UserIsActive" />

【问题讨论】:

  • 你的问题回答了我的问题,谢谢!
  • 复选框的选中状态是否已发布?我必须设置唯一 ID 才能让它工作。

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


【解决方案1】:

这是我大约一年前写的一个版本。我希望能够绑定检查状态以及单个项目的工具提示。希望对你有帮助...

public class CheckBoxList_Extended : CheckBoxList
{
    /// <summary>
    /// Gets or sets the name of the data property to bind to the tooltip attribute of the individual CheckBox.
    /// </summary>
    [DefaultValue("")]
    public string DataTooltipField
    {
        get
        {
            string value = base.ViewState["DataTooltipField"] as string;
            if (value == null)
                value = "";
            return value;
        }
        set
        {
            if (value == null || value.Trim() == "")
            {
                base.ViewState.Remove("DataTooltipField");
            }
            else
            {
                base.ViewState["DataTooltipField"] = value.Trim();
            }
        }
    }
    /// <summary>
    /// Gets or sets the name of the data property to bind to the Checked property of the individual CheckBox.
    /// </summary>
    [DefaultValue("")]
    public string DataCheckedField
    {
        get
        {
            string value = base.ViewState["DataCheckedField"] as string;
            if (value == null)
                value = "";
            return value;
        }
        set
        {
            if (value == null || value.Trim() == "")
            {
                base.ViewState.Remove("DataCheckedField");
            }
            else
            {
                base.ViewState["DataCheckedField"] = value.Trim();
            }
        }
    }

    protected override void PerformDataBinding(System.Collections.IEnumerable dataSource)
    {
        if (dataSource != null)
        {
            string dataSelectedField = this.DataCheckedField;
            string dataTextField = this.DataTextField;
            string dataTooltipField = this.DataTooltipField;
            string dataValueField = this.DataValueField;
            string dataTextFormatString = this.DataTextFormatString;

            bool dataBindingFieldsSupplied = (dataTextField.Length != 0) || (dataValueField.Length != 0);
            bool hasTextFormatString = dataTextFormatString.Length != 0;
            bool hasTooltipField = dataTooltipField.Length != 0;
            bool hasSelectedField = dataSelectedField.Length != 0;

            if (!this.AppendDataBoundItems)
                this.Items.Clear();

            if (dataSource is ICollection)
                this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;

            foreach (object dataItem in dataSource)
            {
                ListItem item = new ListItem();

                if (dataBindingFieldsSupplied)
                {
                    if (dataTextField.Length > 0)
                    {
                        item.Text = DataBinder.GetPropertyValue(dataItem, dataTextField, null);
                    }
                    if (dataValueField.Length > 0)
                    {
                        item.Value = DataBinder.GetPropertyValue(dataItem, dataValueField, null);
                    }
                }
                else
                {
                    if (hasTextFormatString)
                    {
                        item.Text = string.Format(CultureInfo.CurrentCulture, dataTextFormatString, new object[] { dataItem });
                    }
                    else
                    {
                        item.Text = dataItem.ToString();
                    }
                    item.Value = dataItem.ToString();
                }
                if (hasSelectedField)
                {
                    item.Selected = (bool)DataBinder.GetPropertyValue(dataItem, dataSelectedField);
                }
                if (hasTooltipField)
                {
                    string tooltip = DataBinder.GetPropertyValue(dataItem, dataTooltipField, null);
                    if (tooltip != null && tooltip.Trim() != "")
                    {
                        item.Attributes["title"] = tooltip;
                    }
                }
                this.Items.Add(item);
            }
        }
        base.PerformDataBinding(null);
    }
}

【讨论】:

  • 太棒了!我不明白所有这些文章怎么会把这件事弄得这么乱。这正是我所追求的。
  • 我不能把所有的功劳都归功于我,我找到了几篇很好的文章让我了解了这种技术。不幸的是,我没有做笔记,所以我无法将其他人指向他们。 =P
  • 这样一个非常古老但有用的回复。看着这个,我觉得创建一个 RadioButtonList 实现会非常简单,它在绑定时从数据源返回时尊重实际的 ListItem 实例,而不是仅使用值和文本创建新实例。这将为我解决类似的问题,因为我可以轻松地将我的数据转换为 IEnumerable&lt;ListItem&gt;。
  • 我继续上面的想法并创建了一个支持ListItem 实例的控件。它最终工作得很好。更多详情请看这里:stackoverflow.com/questions/50993969/…
【解决方案2】:

Checkbox 已经有一个属性,“Checked”

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.checked.aspx

您可以相当轻松地添加自定义,只需添加一个新的公共属性。然后,您可以通过编程方式或在 aspx 代码中设置它。

public class ListedCheckBoxList : CheckBoxList
{
    public string CustomTag { get; set; }
    //...snip
}

<myControls:myCheckBox runat='server' Checked='True' CustomTag="123test" />

【讨论】:

  • 该字段不是 DataBindable。我已经编辑了我的问题以更好地描述所需的功能。
  • 啊,我明白了,我误会了。很高兴其他人能够提供帮助。
猜你喜欢
  • 2016-03-27
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多