Forked from mattiasnorell/PropertyAppSettingsDropDownList.cs
Created
June 14, 2017 08:30
-
-
Save MichalGrzegorzak/a78ce99d4e8d9f30cf36996f9c331d11 to your computer and use it in GitHub Desktop.
Populate a EPiServer CMS 7 drop down list in dynamic content from AppSettings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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