Skip to content

Instantly share code, notes, and snippets.

@mattiasnorell
Created August 22, 2014 12:53
Show Gist options
  • Save mattiasnorell/d7bdc9347c5d968f4569 to your computer and use it in GitHub Desktop.
Save mattiasnorell/d7bdc9347c5d968f4569 to your computer and use it in GitHub Desktop.
Populate a EPiServer CMS 7 drop down list in dynamic content from AppSettings
using EPiServer.Core;
using EPiServer.PlugIn;
using EPiServer.SpecializedProperties;
using EPiServer.Web.PropertyControls;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.UI.WebControls;
namespace Namespace.Path.In.Project
{
/*
Init using: new PropertyAppSettingsDropDownList { AppSetting = "AppSettingsValue" }
*/
[PropertyDefinitionTypePlugIn(DisplayName = "Dropdown list populated from AppSettings")]
public class PropertyAppSettingsDropDownList : PropertyDropDownList
{
public string AppSetting { get; set; }
public override IPropertyControl CreatePropertyControl()
{
if (string.IsNullOrEmpty(AppSetting))
{
throw new Exception("AppSetting missing.");
}
return new AppSettingsDropDownControl { AppSetting = AppSetting };
}
}
public class AppSettingsDropDownControl : PropertyDropDownListControl
{
public string AppSetting { get; set; }
public PropertyDropDownList DropDownListValue
{
get { return PropertyData as PropertyDropDownList; }
}
protected override void SetupEditControls()
{
Setup();
}
protected virtual void Setup()
{
var selectedValue = string.Empty;
if (DropDownListValue != null && DropDownListValue.Value != null)
{
selectedValue = (string)DropDownListValue.Value;
}
AddListItems(selectedValue);
EditControl.DataBind();
}
protected virtual void AddListItems(string selectedValue = null)
{
var appSettings = ParseAppSettings();
foreach (var item in appSettings)
{
if (item.Value == selectedValue)
{
item.Selected = true;
}
EditControl.Items.Add(item);
}
}
protected IEnumerable ParseAppSettings()
{
var setting = ConfigurationManager.AppSettings[AppSetting];
var list = new List();
foreach (var item in setting.Split('|'))
{
var itemSplit = item.Split(';');
var itemName = itemSplit[0];
var itemId = itemSplit[1];
var returnItem = new ListItem(itemName, itemId);
list.Add(returnItem);
}
return list;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment