AngularJS Select Binding with C# Enum
Problem
I have C# enum.
I have Web API that provides the enum as System.Web.Mvc.SelectListItem
.
And finally, I have AngularJS partial html that uses the enum. core.ClueTypes
holds the result of the Web API.
When I run it, the dropdown shows item list well and it saves the selected value well. But when it loads, ng-model="clue.ClueType"
doesn’t seem to work. It always selects blank item with ?
value.
Angular-rendered HTML content:
What went wrong?
Solution
Clue
class’s ClueType
is int value, and core.ClueTypes
holds string type value for Value
. Instead of raising any error, AngularJS silently ignores the int value.
You can solve it by making these two types match. Here I am giving int type Value
to core.ClueTypes
, making both core.ClueTypes.Value
and clue.ClueType
to be int.
new Web API to return int type Value:
I ended up with my own EnumHelper
since I needed spaces in the Text, which also made my Web API controller code briefer.