| View previous topic :: View next topic |
| Author |
Message |
connorpeterson
Joined: 27 Jan 2008 Posts: 6
|
Posted: Mon Feb 18, 2008 6:39 pm Post subject: Bind enum to select |
|
|
Is there an easy (or recommended) way to bind an Enum to a select list?
I had thought FormHelper.EnumToPairs might work, but unfortunately it looks like thats for something else.
Thanks for any help. |
|
| Back to top |
|
 |
tehlike
Joined: 25 Sep 2007 Posts: 78
|
Posted: Mon Feb 18, 2008 7:22 pm Post subject: |
|
|
| You can implement your own helper with using Enum.GetNames() |
|
| Back to top |
|
 |
connorpeterson
Joined: 27 Jan 2008 Posts: 6
|
Posted: Tue Feb 19, 2008 6:20 pm Post subject: |
|
|
Thanks. Did what you suggested.
Probably a better way to do this, but here's my code for any other noob that needs to do this.
| Code: |
public string Select(string instanceName, Type enumToBind)
{
FormHelper helper = (FormHelper) Controller.Helpers["FormHelper"];
Dictionary<string, string> attributes = new Dictionary<string, string>();
attributes.Add("value", "Id");
attributes.Add("text", "Description");
return helper.Select(instanceName, ConvertEnumToSplitEnum(enumToBind), attributes);
}
|
Works like the FormHelper.Select method, except you pass in the enum to bind. The helper then converts each item in the enum to a simple class, and passes the list of them on to the form helper.
| Code: |
private List<SplitEnum> ConvertEnumToSplitEnum(Type enumToBind)
{
string[] names = Enum.GetNames(enumToBind);
Array values = Enum.GetValues(enumToBind);
List<SplitEnum> bsItems = new List<SplitEnum>();
for (int i = 0; i < values.Length; i++)
{
SplitEnum c = new SplitEnum();
c.Description = names[i];
c.Id = (int)values.GetValue(i);
bsItems.Add(c);
}
return bsItems;
}
public class SplitEnum
{
private int id;
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
}
| [/code] |
|
| Back to top |
|
 |
tehlike
Joined: 25 Sep 2007 Posts: 78
|
Posted: Tue Feb 19, 2008 7:10 pm Post subject: |
|
|
Sorry, it was my bad. There is a way but it is loooong. The way you achieved is shorter, though.
$FormHelper.Select("option", $FormHelper.EnumToPairs($EnumType), $DictHelper.Create("value=First", "text=Second")) |
|
| Back to top |
|
 |
|