…meie igapäevast IT’d anna meile igapäev…

2011-05-12

ASP.NET MVC: Enum binding helper

Filed under: ASP.NET MVC — Sander @ 12:32:01
Tags: ,

Binding enums in the modelbinder is a just bit different than other values, so I wrote another small method for enums into my BinderHelper:

public T GetEnum<T>(string keyName, T defaultValue) where T : struct
{
	if (string.IsNullOrEmpty(ValueCollection[keyName]))
		return defaultValue;  
	var value = ValueCollection[keyName];   
	Enum.TryParse(value, true, out defaultValue);
	return defaultValue;
}

ValueCollection is a NameValueCollection, like described in the BinderHelper post linked above.

Using it is simple:

myModel.EnumValue = _binder.GetEnum("EnumValue", MyEnum.DefaultValue);

Create a free website or blog at WordPress.com.