N2 radiobuttonlist attribute

N2 radiobuttonlist attribute


A radio button list attribute is much simpler to implement then the checkbox list attribute, as only one option is being persisted.

UpdateEditor checks whether the radio button list has a selected value. If so, it sets the selected item of the radio button list.

UpdateItem sets the selected value for the content item.

AddEditor has its data source set to a selection of content items, and adds the a radio button list to the editor interface.


public class EditableRadioListAttribute : AbstractEditableAttribute
{
    public override void UpdateEditor(N2.ContentItem item, Control editor)
    {
        RadioButtonList rbl = editor as RadioButtonList;
        if (rbl != null)
        {
            rbl.SelectedValue = item[this.Name].ToString();
            if (rbl.Items.FindByValue(item[this.Name].ToString()) != null)
            {
                rbl.Items.FindByValue(item[this.Name].ToString()).Selected = true;
            }
        }
    }

    public override bool UpdateItem(N2.ContentItem item, Control editor)
    {
        RadioButtonList rbl = editor as RadioButtonList;
        string itemID = rbl.SelectedValue;
        item[this.Name] = itemID;
        return true;
    }

    protected override Control AddEditor(Control container)
    {
        RadioButtonList rbl = new RadioButtonList();
        var items = N2.Find.Items
            .Where.Type.Eq(typeof(TestItem))
            .Filters(new NavigationFilter())
            .Select();
        foreach (TestItem i in items)
        {
            rbl.Items.Add(new ListItem(i.Title, i.ID.ToString()));
        }
        container.Controls.Add(rbl);
        return rbl;
    }
}

And here is how to use the radio button list attribute


[EditableRadioListAttribute(Title = "Item")]
public virtual string Item
{
    get { return (string)(GetDetail("Item", "")); }
    set { SetDetail("Item", value, ""); }
}

Below is an even simpler way of a creating a radio button list attribute using the N2 EditorModifier


[Editable("Template", typeof(RadioButtonList), "SelectedValue", 5, DataBind = true)]
[EditorModifier("DataSource", new string[] {"Template 1", "Template 2", "Template 3"})]
public virtual string Template
{
            get { return (string)(GetDetail("EmailTemplate") ?? "Template 1"); }
            set { SetDetail("EmailTemplate", value); }
}

In fact, this can also be used for a dropdown list.